MPDialog.openWaiting();
$(function() {

    App.login(function() {
        App.initKeepSession();
        App.initLang();
        App.initUserName();
        App.initSelect2();
        App.initSelect2Multiple();
        setTimeout(function() {
            MPDialog.closeWaiting();
        }, 1000);

        var userInfo = App.getUserInfo();
        if (userInfo.role == 1) {
            $('[data-role="1"]').show();
        } else {
            $('[data-role="1"]').hide();
        }

        // 工作台
        workstation();

        // 左侧菜单
        // 面板切换
        $('.mp-menu [data-panel-class]').each(function (i, el) {
            $(el).click(function (e) {
                // 菜单
                $('.mp-menu [data-panel-class]').removeClass('active');
                $(this).addClass('active');
                // 面板
                $('.mp-panel').removeClass('mp-panel-visible');
                var targetPanelClass = $(this).data('panelClass');
                var targetPanel = $('.' + targetPanelClass);
                targetPanel.addClass('mp-panel-visible');
                var targetParentTitle = $(this).data('parentTitle');
                var targetBookMode = $(this).data('bookMode');
                if (targetParentTitle) {
                    $('.mp-panel-parent-title', targetPanel).parent().remove();
                    $('.mp-panel-title', targetPanel).prepend(
                        $('<li/>')
                            .append(
                                $('<a href="#" class="mp-panel-parent-title"/>')
                                    .html(targetParentTitle)
                            )
                    );
                    if (targetBookMode) {
                        $('.mp-panel-parent-title', targetPanel).attr('data-book-mode', targetBookMode);
                        App.setBookMode(targetBookMode);
                    }
                }

                $('html,body').animate({scrollTop: 0}, 200);

                // // 初始化面板
                // if (targetPanel.hasClass('mp-panel-init')) {
                //     return;
                // }
                $('.mp-panel-article-edit-title').hide();

                removeScrollListener('mp-post-attr-title');
                removeScrollListener('mp-post-attr');
                removeScrollListener('mp-panel-folder-float');
                $('.mp-panel-folder-float').hide();
                $('.mp-panel-article-edit-title').hide();

                imageViewListClear();
                videoViewListClear();

                switch (targetPanelClass) {
                    case 'mp-panel-material-image':
                        $('.mp-panel-material-image form')[0].reset();
                        imageViewList();
                        targetPanel.addClass('mp-panel-init');
                        $('.mp-panel-material-image .mp-search').unbind().click(function () {
                            imageViewList();
                        });
                        break;
                    case 'mp-panel-material-video':
                        $('.mp-panel-material-video form')[0].reset();
                        videoViewList();
                        targetPanel.addClass('mp-panel-init');
                        $('.mp-panel-material-video .mp-search').unbind().click(function () {
                            videoViewList();
                        });
                        break;
                    case 'mp-panel-category':
                        $('.mp-panel-category form')[0].reset();
                        $('.mp-panel-category form select').change();
                        foldersViewList();
                        targetPanel.addClass('mp-panel-init');
                        $('.mp-panel-category .mp-search').unbind().click(function () {
                            foldersViewList('search');
                        });
                        break;
                    case 'mp-panel-tag-category':
                        $('.mp-panel-tag-category form')[0].reset();
                        tagCategoryViewList();
                        targetPanel.addClass('mp-panel-init');
                        break;
                    case 'mp-panel-tag':
                        $('.mp-panel-tag form')[0].reset();
                        $('.mp-panel-tag form select').change();
                        tagViewList();
                        targetPanel.addClass('mp-panel-init');
                        $('.mp-panel-tag .mp-search').unbind().click(function () {
                            tagViewList();
                        });
                        break;
                    case 'mp-panel-email-settings':
                        $('.mp-panel-email-settings form')[0].reset();
                        $('.mp-panel-email-settings form select').change();
                        emailSettingsView();
                        targetPanel.addClass('mp-panel-init');
                        break;
                    case 'mp-panel-article-list':
                        $('.mp-panel-article-list form')[0].reset();
                        articleViewList();
                        targetPanel.addClass('mp-panel-init');
                        $('.mp-panel-article-list .mp-search').unbind().click(function () {
                            articleViewList();
                        });
                        break;
                    case 'mp-panel-folder':
                        foldersTreeView();
                        targetPanel.addClass('mp-panel-init');
                        $('.mp-panel-folder-float .mp-panel-parent-title').parent().remove();
                        $('.mp-panel-folder-float .mp-panel-title').prepend(
                            $('<li/>')
                                .append(
                                    $('<a href="#" class="mp-panel-parent-title"/>')
                                        .html(targetParentTitle)
                                )
                        );
                        break;
                    case 'mp-panel-users':
                        accountViewList();
                        targetPanel.addClass('mp-panel-init');
                        break;
                    case 'mp-panel-release':
                        releaseViewList();
                        break;
                    case 'mp-panel-release-history':
                        historyReleaseViewList();
                        break;
                    case 'mp-panel-dashboard':
                        workstation();
                        break;
                    case 'mp-panel-advice':
                        adviceViewList(0);
                        targetPanel.addClass('mp-panel-init');
                    case 'mp-panel-domains':
                        domainViewList();
                        targetPanel.addClass('mp-panel-init');
                    default:
                }
            });
        });

        // 上传图片
        $('.mp-panel-material-image .mp-upload-button').click(function () {
            MPDialog.materialUploadImage({
                callback: function () {
                    imageViewList();
                }
            });
        });

        // 上传视频
        $('.mp-panel-material-video .mp-upload-button').click(function () {
            MPDialog.materialUploadVideo({
                callback: function () {
                    videoViewList();
                }
            });
        });

        // 添加分类（目录）
        $('.mp-panel-category .mp-category-append').click(function () {
            MPDialog.categoryAppend({
                confirmCallback: function () {
                    foldersViewList();
                }
            });
        });

        // 添加标签
        $('.mp-panel-tag .mp-tag-append').click(function () {
            MPDialog.tagAppend({
                confirmCallback: function () {
                    tagViewList();
                }
            });
        });

        // 添加标签分类
        $('.mp-panel-tag-category .mp-tag-category-append').click(function () {
            MPDialog.tagCategoryAppend({
                confirmCallback: function () {
                    tagCategoryViewList();
                }
            });
        });

        // 添加用户
        $('.mp-panel-users .mp-users-append').click(function () {
            MPDialog.userAppend({
                confirmCallback: function () {
                    accountViewList();
                }
            });
        });

        // 修改当前登录用户信息
        $('.mp-login-user').click(function() {
            var m = App.getUserInfo();
            MPDialog.userPassword({});
        });

        // 文章管理.添加文章 ok
        // 添加文章
        eventNavigationPanel({
            eventTargetElement: $('.mp-panel-article-list .mp-append-post-button'),
            firstPanelElement: $('.mp-panel-article-list'),
            secondPanelElement: $('.mp-panel-article-edit'),
            finishCallback: function (firstPanelElement, secondPanelElement, eventTargetElement) {
                var saveArticle = function (finishCallback) {
                    var data = formValueForArticle();
                    var checkResult = vaildateForArticle(data);
                    if (!checkResult.result) {
                        $('.mp-danger-alert-message').html(checkResult.message).closest('.row').show();
                        return false;
                    } else {
                        $('.mp-danger-alert-message').closest('.row').hide();
                    }
                    data.siteId = App.getSiteId();
                    data.lang = App.getLang();
                    if (data.id) {
                        // TODO update
                        Apis.updateArticle(data, function (response) {
                            finishCallback && finishCallback();
                            $('.mp-success-alert-message').html('已保存').closest('.row').show();
                            $('.mp-panel-article-edit .mp-post-info [name="id"]').val(response.data);
                            MPDialog.alert({
                                message: '已保存'
                            });
                            $('.mp-preview', secondPanelElement).show();
                            intoArticleUpdateMode(response.data);
                            articleViewList();
                        });
                    } else {
                        // TODO create
                        Apis.createArticle(data, function (response) {
                            finishCallback && finishCallback();
                            $('.mp-success-alert-message').html('已保存').closest('.row').show();
                            $('.mp-panel-article-edit .mp-post-info [name="id"]').val(response.data);
                            MPDialog.alert({
                                message: '已保存'
                            });
                            $('.mp-preview', secondPanelElement).show();
                            intoArticleUpdateMode(response.data);
                            articleViewList();
                        });
                    }
                    return false;
                };
                eventNavigationSubmit(firstPanelElement, secondPanelElement, function () {
                    var data = formValueForArticle();
                    var parameter = {
                        siteId: App.getSiteId(),
                        lang: App.getLang(),
                        articleNo: data.articleNo,
                        fileName: data.fileName,
                        title: data.title
                    };
                    Apis.isExistArticle(parameter, function(response) {
                        if (response.data > 0) {
                            MPDialog.alert({
                                message: '文章已存在'
                            });
                            return;
                        }
                        saveArticle();
                    });
                    return false;
                });
                eventNavigationCancel(firstPanelElement, secondPanelElement, function () {
                    articleViewList();
                    removeScrollListener('mp-post-attr-title');
                    removeScrollListener('mp-post-attr');
                    removeScrollListener('mp-panel-folder-float');
                    $('.mp-panel-article-edit-title').hide();
                });

                // 设置面板标题
                $('.mp-panel-title a', secondPanelElement).html('添加文章');

                // 预览
                $('.mp-preview', secondPanelElement).unbind().hide().click(function () {
                    var form = $('.mp-panel-article-edit form.mp-post-info');
                    var id = formValue(form).id;
                    // window.open('preview/mockup/book.html?id=' + id, '_blank');
                    window.open('../manual/article.html?siteId=' + App.getSiteId() + '&lang=' + App.getLang() + '&articleId=' + id, '_blank');
                });

                // 还原编辑面板
                $('.mp-panel-article-edit [data-post-panel-class]').removeClass('active');
                $('.mp-panel-article-edit [data-post-panel-class="mp-post-attribute"]').addClass('active');
                $('.mp-panel-article-edit form').removeClass('mp-panel-visible');
                $('.mp-panel-article-edit form.mp-post-attribute').addClass('mp-panel-visible');
                initPostBefore();

                // 全部初始化
                {
                    $('.mp-panel-article-edit [data-post-panel-class]').each(function (i, tab) {
                        var targetPanelClass = $(tab).data('postPanelClass');
                        var targetPanel = $('.mp-panel-article-edit .' + targetPanelClass);
                        targetPanel.addClass('mp-panel-visible');
                        if (targetPanelClass == 'mp-post-step-standard') {
                            return;
                        }
                        targetPanel.addClass('mp-panel-init');
                    });

                    // 文章属性
                    initPostAttribute();
                    // 摘要
                    initPostSummary();
                    // 流程简述
                    initPostProcessStep();
                    // 操作范例
                    // targetPanel.addClass('mp-panel-init');
                    initPostStepStandard();
                    // 图片
                    initPostImage();
                    // 视频
                    initPostVideo();
                    // 备注
                    initPostRemark();
                    // 相关文章
                    initPostRelatedPost();
                    // 相关视频
                    initPostRelatedVideo();
                    // 标签
                    initPostTag();

                    // 还原编辑面板
                    $('.mp-panel-article-edit [data-post-panel-class]').removeClass('active');
                    $('.mp-panel-article-edit [data-post-panel-class="mp-post-attribute"]').addClass('active');
                    $('.mp-panel-article-edit form').removeClass('mp-panel-visible');
                    $('.mp-panel-article-edit form.mp-post-attribute').addClass('mp-panel-visible');
                }

                // 文章编辑.面板切换
                $('.mp-panel-article-edit [data-post-panel-class]').each(function (i, el) {
                    $(el).unbind().click(function (e) {
                        // 菜单
                        $('.mp-panel-article-edit [data-post-panel-class]').removeClass('active');
                        $(this).addClass('active');
                        // 面板
                        $('.mp-panel-article-edit form').removeClass('mp-panel-visible');
                        var targetPanelClass = $(this).data('postPanelClass');
                        var targetPanel = $('.mp-panel-article-edit .' + targetPanelClass);
                        targetPanel.addClass('mp-panel-visible');
                        switch (targetPanelClass) {
                            case 'mp-post-summary': // 摘要
                            case 'mp-post-step-standard': // 操作范例
                            case 'mp-post-remark': // 备注
                            default:
                                CurrUEditor = null;
                        }
                        if (targetPanel.hasClass('mp-panel-init')) {
                            return;
                        }
                        switch (targetPanelClass) {
                            case 'mp-post-attribute':
                                // 文章属性
                                targetPanel.addClass('mp-panel-init');
                                initPostAttribute();
                                break;

                            case 'mp-post-summary':
                                // 摘要
                                targetPanel.addClass('mp-panel-init');
                                initPostSummary();
                                break;

                            case 'mp-post-process-step':
                                // 流程简述
                                targetPanel.addClass('mp-panel-init');
                                initPostProcessStep();
                                break;

                            case 'mp-post-step-standard':
                                // 操作范例
                                // targetPanel.addClass('mp-panel-init');
                                initPostStepStandard();
                                break;

                            case 'mp-post-image':
                                // 图片
                                targetPanel.addClass('mp-panel-init');
                                initPostImage();
                                break;

                            case 'mp-post-video':
                                // 视频
                                targetPanel.addClass('mp-panel-init');
                                initPostVideo();
                                break;

                            case 'mp-post-remark':
                                // 备注
                                targetPanel.addClass('mp-panel-init');
                                initPostRemark();
                                break;

                            case 'mp-post-related-post':
                                // 相关文章
                                targetPanel.addClass('mp-panel-init');
                                initPostRelatedPost();
                                break;

                            case 'mp-post-related-video':
                                // 相关视频
                                targetPanel.addClass('mp-panel-init');
                                initPostRelatedVideo();
                                break;

                            case 'mp-post-tag':
                                // 标签
                                targetPanel.addClass('mp-panel-init');
                                initPostTag();
                                break;
                            default:
                        }
                    });
                });

                initPostPanelToolsbar();
            }
        });

    });
});

/** **************************************************************************************************** 工作台 */

function workstation() {
    // Apis.getConsoleCount({lang: App.getLang(), siteId: App.getSiteId()}, function(response) {
    //     $('.tv-imageCount').html(response.data.imageCount);
    //     $('.tv-videoCount').html(response.data.videoCount);
    //     $('.tv-moldArticleCount').html(response.data.moldArticleCount);
    //     $('.tv-pressArticleCount').html(response.data.pressArticleCount);
    // });
    MPDialog.openWaiting();
    Apis.getConsoleCount({lang: App.getLang(), siteId: App.getSiteId()}, function(response) {
        setTimeout(function() {
            MPDialog.closeWaiting();
        }, 1000);

        var list = response.data && response.data.counts ? response.data.counts : [];
        var productCount = 0;
        var newsCount = 0;
        var contactCount = 0;
        list.forEach(function(item) {
            if (item.folderName === '产品') {
                productCount = item.count;
            }
            else if (item.folderName === '新闻') {
                newsCount = item.count;
            }
            else if (item.folderName === '咨询') {
                contactCount = item.count;
            }
        });
        $('.tv-productCount').html(productCount);
        $('.tv-newsCount').html(newsCount);
        $('.tv-contactCount').html(contactCount);
    });
}


/** **************************************************************************************************** 素材 */

function fcloud(options) {
    var defatutOptions = {
        url: null,
        fileInputJqObj: null,
        formJqObj: null,
        submitCallback: null,
        progressCallback: function(uniqueId, progress) {},
        progressAllCallback: function(progress) {},
        doneCallback: function(uniqueId, response) {},
        doneAllCallback: function() {},
    };
    var opts = $.extend(defatutOptions, options);
    opts.fileInputJqObj.FCloudUpload({
        url: opts.url,
        autoUpload: false,
        upload: function(data) {
            if (opts.submitCallback) {
                opts.submitCallback(data);
            } else {
                data.submit();
            }
        },
        // onFormData: (function () {
        //     if (formJqObj) {
        //         return function (form) {
        //             // return $('#DataForm').serializeArray();
        //             return $.param(formValue(formJqObj));
        //         }
        //     }
        //     return null;
        // })(),
        onChange: function (e, data) {

        },
        onAppend: function (e, data, uniqueId, file) {

            // $('#files-console-log')
            //     .append(
            //         $('<p/>')
            //             .append(file.name + ': ')
            //             .append(
            //                 $('<code/>').attr('id', 'progress-number-' + uniqueId).html('none%')
            //             )
            //     )
            //     .append(
            //         $('<div class="progress active"/>')
            //             .append(
            //                 $(progs).attr('id', 'progress-bar-' + uniqueId)
            //             )
            //     );

        },
        onProgress: function (e, data, uniqueId, file, progress) {

            // $('#progress-number-' + uniqueId).html(progress + '%');
            // $('#progress-bar-' + uniqueId).attr('aria-valuenow', progress);
            // $('#progress-bar-' + uniqueId).css('width', progress + '%');
            // $('#progress-bar-' + uniqueId).addClass('progress-bar-striped');
            // if (progress == 100) {
            //     $('#progress-bar-' + uniqueId).removeClass('progress-bar-striped');
            // }

            if (opts.progressCallback) {
                opts.progressCallback(uniqueId, progress);
            }

        },
        onProgressAll: function (e, data, progress) {
            // $('#progress-number').html(progress + '%');
            // $('#progress-bar').attr('aria-valuenow', progress);
            // $('#progress-bar').css('width', progress + '%');
            // $('#progress-bar').addClass('progress-bar-striped');
            // if (progress == 100) {
            //     $('#progress-number').html('100% Complete');
            //     $('#progress-bar').removeClass('progress-bar-striped');
            // }

            if (opts.progressAllCallback) {
                opts.progressAllCallback(progress);
            }
        },
        onDone: function (e, data, uniqueId, file, response_data) {
            if (opts.doneCallback) {
                opts.doneCallback(uniqueId, response_data);
            }
        },
        onFail: function (e, data) {
        },
        onAlways: function (e, data) {
        },
        onDoneAll: function (e, data) {
            if (opts.doneAllCallback) {
                opts.doneAllCallback();
            }
        },
    });
}

// 显示图片素材列表
function imageViewList(pageIndex) {
    var pageSize = 100;

    var panelElement = $('.mp-panel-material-image');
    var contentElement = $('.mp-panel-content', panelElement).empty();

    MPDialog.openWaiting();
    var build = function(response) {
        setTimeout(function() {
            MPDialog.closeWaiting();
        }, 1000);

        var page = Pagination({
            pageStart: pageIndex,
            pageSize: pageSize,
            totalSize: response.data.totalCount
        }, function(index) {
            imageViewList(index);
        });
        $('.pagination', panelElement).parent().empty()
            .append(page);

        $('.mp-count', panelElement).html(response.data.totalCount);

        var list = response.data ? response.data.forms : [];

        var rowElement = $('<div class="row"/>');
        var listContentElement = $('<div class="col-xs-12"/>').appendTo(rowElement);

        if (!list || list.length == 0) {
            contentElement.empty().append(rowElement);
            return;
        }

        list.forEach(function(m) {
            listContentElement.append(
                $('<div class="mp-box-block">')
                    .append(
                        $('<div class="mp-box-top-toolbar"/>')
                            .append(
                                $('<img class="mp-remove" src="theme/images/icon-remove.png">')
                                    .data(m)
                                    .click(function() {
                                        var img = $(this);
                                        var m = img.data();
                                        MPDialog.confirm({
                                            message: '确认删除?',
                                            confirmCallback: function() {
                                                Apis.deleteResImage({uid: m.uid, type: 0}, function(response) {
                                                    img.closest('.mp-box-block').remove();
                                                });
                                            }
                                        });
                                    })
                            )
                    )
                    .append(
                        $('<div class="mp-image-box"/>').append(
                            $('<img class="img-rounded mp-image" src="theme/images/preview.png" data-holder-rendered="true"/>')
                                .data(m)
                                .attr('alt', m.name)
                                .attr('src', m.url)
                                .attr('onerror', 'this.src="theme/images/preview.png"')
                                .click(function(e) {
                                    var m = $(this).data();
                                    MPDialog.preview({
                                        content: function(build) {
                                            var content = $('<div/>')
                                                .css('text-align', 'center');
                                            build(content);

                                            var image = document.createElement('img');
                                            image.src = m.url;
                                            image.onload = function() {
                                                var maxWidth = content.width();
                                                var maxHeight = 500;
                                                var s = maxHeight / image.height;
                                                var w = image.width * s;
                                                var h = maxHeight;
                                                if (w > maxWidth) {
                                                    s = maxWidth / image.width;
                                                    w = maxWidth;
                                                    h = image.height * s;
                                                }
                                                $(image)
                                                    .css({
                                                        width: w + 'px',
                                                        height: h + 'px'
                                                    })
                                                    .appendTo(content);
                                            };
                                        }
                                    });
                                })
                        )
                    )
                    .append(
                        $('<div class="mp-name-input"/>').append(
                            $('<input type="text"/>')
                                .val(m.file)
                                .data(m)
                                .change(function() {
                                    var m = $(this).data();
                                    var name = this.value;
                                    Apis.renameResImage({
                                        siteId: App.getSiteId(),
                                        lang: App.getLang(),
                                        uid: m.uid,
                                        name: name
                                    }, function(response) {

                                    });
                                })
                        )
                    )
                    .append(
                        $('<div class="mp-name"/>').append((function() {
                            var value = [
                                m.name,
                                moment(m.created).format('YYYY-MM-DD HH:mm:ss')
                            ];
                            return value.join('<br />');
                        })())
                    )
            );
        });

        contentElement.empty().append(rowElement);
    };

    var condition = formValue($('.mp-panel-material-image form'));
    condition.siteId = App.getSiteId();
    condition.lang = App.getLang();
    condition.pageStart = pageIndex * pageSize;
    condition.pageSize = pageSize;
    if (condition.name) {
        Apis.getResImagesSearch(condition, function(response) {
            build(response);
        });
    } else {
        Apis.getResImages(condition, function(response) {
            build(response);
        });
    }

    var sortCreateAt = $('.mp-sort-by-create_at', panelElement);
    var sortName = $('.mp-sort-by-name', panelElement);
    sortCreateAt.unbind().click(function() {
        sortName.removeClass('mp-sort-selected').find('.iconfont').remove();
        sortCreateAt.addClass('mp-sort-selected').find('.iconfont').remove();
        var ascOrDes = sortCreateAt.data('order');
        if (ascOrDes == 'desc') {
            ascOrDes = true;
            sortCreateAt.attr('order', 'asc');
            sortCreateAt.data('order', 'asc');
            sortCreateAt.append('<i class="icon iconfont"></i>');
            $('.iconfont', sortCreateAt).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-shengxu');
        } else {
            ascOrDes = false;
            sortCreateAt.attr('order', 'desc');
            sortCreateAt.data('order', 'desc');
            sortCreateAt.append('<i class="icon iconfont"></i>');
            $('.iconfont', sortCreateAt).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-jiangxu');
        }
        var orders = [
            {
                field: 'create_at',
                ascOrDes: ascOrDes
            }
        ];

        var condition = formValue($('.mp-panel-material-image form'));
        condition.siteId = App.getSiteId();
        condition.lang = App.getLang();
        condition.pageStart = pageIndex * pageSize;
        condition.pageSize = pageSize;
        condition.orders = orders;
        if (condition.name) {
            Apis.getResImagesSearch(condition, function(response) {
                build(response);
            });
        } else {
            Apis.getResImages(condition, function(response) {
                build(response);
            });
        }
    });
    sortName.unbind().click(function() {
        sortName.addClass('mp-sort-selected').find('.iconfont').remove();
        sortCreateAt.removeClass('mp-sort-selected').find('.iconfont').remove();
        var ascOrDes = sortName.data('order');
        if (ascOrDes == 'desc') {
            ascOrDes = true;
            sortName.attr('order', 'asc');
            sortName.data('order', 'asc');
            sortName.append('<i class="icon iconfont"></i>');
            $('.iconfont', sortName).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-shengxu');
        } else {
            ascOrDes = false;
            sortName.attr('order', 'desc');
            sortName.data('order', 'desc');
            sortName.append('<i class="icon iconfont"></i>');
            $('.iconfont', sortName).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-jiangxu');
        }
        var orders = [
            {
                field: 'name',
                ascOrDes: ascOrDes
            }
        ];

        var condition = formValue($('.mp-panel-material-image form'));
        condition.siteId = App.getSiteId();
        condition.lang = App.getLang();
        condition.pageStart = pageIndex * pageSize;
        condition.pageSize = pageSize;
        condition.orders = orders;
        if (condition.name) {
            Apis.getResImagesSearch(condition, function(response) {
                build(response);
            });
        } else {
            Apis.getResImages(condition, function(response) {
                build(response);
            });
        }
    });

}
function imageViewListClear() {
    $('.mp-panel-material-image .mp-panel-content').empty();
}

// 显示视频素材列表
function videoViewList(pageIndex) {
    var pageSize = 100;

    var panelElement = $('.mp-panel-material-video');
    var contentElement = $('.mp-panel-content', panelElement).empty();

    MPDialog.openWaiting();
    var build = function(response) {
        setTimeout(function() {
            MPDialog.closeWaiting();
        }, 1000);

        var page = Pagination({
            pageStart: pageIndex,
            pageSize: pageSize,
            totalSize: response.data.totalCount
        }, function(index) {
            videoViewList(index);
        });
        $('.pagination', panelElement).parent().empty()
            .append(page);

        $('.mp-count', panelElement).html(response.data.totalCount);

        var list = response.data ? response.data.forms : [];

        var rowElement = $('<div class="row"/>');
        var listContentElement = $('<div class="col-xs-12"/>').appendTo(rowElement);

        if (!list || list.length == 0) {
            contentElement.empty().append(rowElement);
            return;
        }

        list.forEach(function(m) {
            listContentElement.append(
                $('<div class="mp-box-block">')
                    .append(
                        $('<div class="mp-box-top-toolbar"/>')
                            .append(
                                $('<img class="mp-remove" src="theme/images/icon-remove.png">')
                                    .data(m)
                                    .click(function() {
                                        var img = $(this);
                                        var m = img.data();
                                        MPDialog.confirm({
                                            message: '确认删除?',
                                            confirmCallback: function() {
                                                Apis.deleteResVideo({uid: m.uid, type: 1}, function(response) {
                                                    img.closest('.mp-box-block').remove();
                                                });
                                            }
                                        });
                                    })
                            )
                    )
                    .append(
                        $('<div class="mp-video-box"/>').append(
                            $('<img class="img-rounded mp-image" src="theme/images/preview-video.png" data-holder-rendered="true"/>')
                                .data(m)
                                .attr('alt', m.name)
                                .attr('onerror', 'this.src="theme/images/preview-video.png"')
                                .click(function(e) {
                                    var m = $(this).data();
                                    MPDialog.preview({
                                        content: function(build) {
                                            var content = $('<video class="post-video" controls="controls" preload="auto" width="100%" autoplay="autoplay"/>');
                                            // medias/video.mp4
                                            content.append(
                                                $('<source src="" type="video/mp4"/>')
                                                    .attr('src', m.playurl)
                                            );
                                            build(content);
                                        }
                                    });
                                })
                        )
                    )
                    .append(
                        $('<div class="mp-name-input"/>').append(
                            $('<input type="text"/>')
                                .val(m.file)
                                .data(m)
                                .change(function() {
                                    var m = $(this).data();
                                    var name = this.value;
                                    Apis.renameResVideo({
                                        siteId: App.getSiteId(),
                                        lang: App.getLang(),
                                        uid: m.uid,
                                        name: name
                                    }, function(response) {

                                    });
                                })
                        )
                    )
                    .append(
                        $('<div class="mp-name"/>').append((function() {
                            var value = [
                                m.name,
                                moment(m.created).format('YYYY-MM-DD HH:mm:ss')
                            ];
                            return value.join('<br />');
                        })())
                    )
            );
        });

        contentElement.empty().append(rowElement);

        // 缩略图
        var images = $('.mp-image', rowElement);
        var count = images.length;
        var index = 0;
        var ci = new Chain();
        images.each(function() {
            ci.method(function(next, _) {
                var m = $(images[index]).data();
                new VideoScreenshot({
                    url: m.playurl,
                    type: 'video/mp4',
                    image: images[index],
                    callback: function(base64image) {
                        // $('<img id="m-image" width="500" />')
                        //     .attr('src', base64image)
                        //     .css('display', 'block')
                        //     .appendTo(listElement);
                    }
                });
                index++;
                next();
            });
        });
        ci.method(function() {
            runVideoScreenshotQueue();
        })
        ci.start();

    };

    var condition = formValue($('.mp-panel-material-video form'));
    condition.siteId = App.getSiteId();
    condition.lang = App.getLang();
    condition.pageStart = pageIndex * pageSize;
    condition.pageSize = pageSize;
    if (condition.name) {
        Apis.getResVideosSearch(condition, function(response) {
            build(response);
        });
    } else {
        Apis.getResVideos(condition, function(response) {
            build(response);
        });
    }

    var sortCreateAt = $('.mp-sort-by-create_at', panelElement);
    var sortName = $('.mp-sort-by-name', panelElement);
    sortCreateAt.unbind().click(function() {
        sortName.removeClass('mp-sort-selected').find('.iconfont').remove();
        sortCreateAt.addClass('mp-sort-selected').find('.iconfont').remove();
        var ascOrDes = sortCreateAt.data('order');
        if (ascOrDes == 'desc') {
            ascOrDes = true;
            sortCreateAt.attr('order', 'asc');
            sortCreateAt.data('order', 'asc');
            sortCreateAt.append('<i class="icon iconfont"></i>');
            $('.iconfont', sortCreateAt).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-shengxu');
        } else {
            ascOrDes = false;
            sortCreateAt.attr('order', 'desc');
            sortCreateAt.data('order', 'desc');
            sortCreateAt.append('<i class="icon iconfont"></i>');
            $('.iconfont', sortCreateAt).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-jiangxu');
        }
        var orders = [
            {
                field: 'create_at',
                ascOrDes: ascOrDes
            }
        ];

        var condition = formValue($('.mp-panel-material-video form'));
        condition.siteId = App.getSiteId();
        condition.lang = App.getLang();
        condition.pageStart = pageIndex * pageSize;
        condition.pageSize = pageSize;
        condition.orders = orders;
        if (condition.name) {
            Apis.getResVideosSearch(condition, function(response) {
                build(response);
            });
        } else {
            Apis.getResVideos(condition, function(response) {
                build(response);
            });
        }
    });
    sortName.unbind().click(function() {
        sortName.addClass('mp-sort-selected').find('.iconfont').remove();
        sortCreateAt.removeClass('mp-sort-selected').find('.iconfont').remove();
        var ascOrDes = sortName.data('order');
        if (ascOrDes == 'desc') {
            ascOrDes = true;
            sortName.attr('order', 'asc');
            sortName.data('order', 'asc');
            sortName.append('<i class="icon iconfont"></i>');
            $('.iconfont', sortName).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-shengxu');
        } else {
            ascOrDes = false;
            sortName.attr('order', 'desc');
            sortName.data('order', 'desc');
            sortName.append('<i class="icon iconfont"></i>');
            $('.iconfont', sortName).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-jiangxu');
        }
        var orders = [
            {
                field: 'name',
                ascOrDes: ascOrDes
            }
        ];

        var condition = formValue($('.mp-panel-material-video form'));
        condition.siteId = App.getSiteId();
        condition.lang = App.getLang();
        condition.pageStart = pageIndex * pageSize;
        condition.pageSize = pageSize;
        condition.orders = orders;
        if (condition.name) {
            Apis.getResVideosSearch(condition, function(response) {
                build(response);
            });
        } else {
            Apis.getResVideos(condition, function(response) {
                build(response);
            });
        }
    });

}
function videoViewListClear() {
    $('.mp-panel-material-video .mp-panel-content').empty();
}

/** **************************************************************************************************** 标签分类 & 标签 */

// 显示标签分类列表
function tagCategoryViewList() {

    var panelElement = $('.mp-panel-tag-category');
    var listContianer = $('table tbody', panelElement).empty();

    MPDialog.openWaiting();
    var build = function(response) {
        setTimeout(function() {
            MPDialog.closeWaiting();
        }, 1000);

        var list = response.data ? response.data.catalogs : [];

        if (!list || list.length == 0) {
            return;
        }

        list.forEach(function(m) {
            var row = $('<tr/>').appendTo(listContianer);
            row.data('value', m);
            $('<td/>').html(m.name).appendTo(row);
            $('<td/>')
                .append(
                    $('<button type="button" class="btn btn-warning btn-xs">修改</button>')
                        .click(function(e) {
                            var m = $(this).closest('tr').data('value');
                            MPDialog.tagCategoryAppend({
                                data: m,
                                confirmCallback: function() {
                                    tagCategoryViewList();
                                }
                            });
                        })
                )
                .append(
                    $('<button type="button" class="btn btn-danger btn-xs">删除</button>')
                        .click(function(e) {
                            var m = $(this).closest('tr').data('value');
                            MPDialog.confirm({
                                message: '确认删除?',
                                confirmCallback: function() {
                                    if (App.getLang() == 'zhCN') {
                                        var parameter = {
                                            siteId: App.getSiteId(),
                                            lang: App.getLang(),
                                            id: m.id
                                        };
                                        Apis.getTagCategotyLangAll(parameter, function(response) {
                                            var list = response.data;
                                            var id = [];
                                            list.forEach(function(m) {
                                                id.push(m.id);
                                            });
                                            var parameter = {
                                                id: id
                                            };
                                            Apis.delTagCategotyLangAll(parameter, function(response) {
                                                tagCategoryViewList();
                                            });
                                        });
                                        return;
                                    }
                                    Apis.delTagCategoty({id: m.id}, function() {
                                        tagCategoryViewList();
                                    });
                                }
                            });
                        })
                )
                .appendTo(row);
        });
    };

    var condition = {};
    condition.lang = App.getLang();
    condition.siteId = App.getSiteId();
    condition.start = 0;
    condition.size = 99999;
    Apis.getTagCategotys(condition, function(response) {
        build(response);
    });

}

// 显示标签列表
function tagViewList() {

    var panelElement = $('.mp-panel-tag');
    var listContianer = $('table tbody', panelElement).empty();

    MPDialog.openWaiting();
    var build = function(response) {
        setTimeout(function() {
            MPDialog.closeWaiting();
        }, 1000);

        var list = response.data ? response.data.tags : [];

        if (!list || list.length == 0) {
            return;
        }

        list.forEach(function(m) {
            var row = $('<tr/>').appendTo(listContianer);
            row.data('value', m);
            $('<td/>').html(m.name).appendTo(row);
            $('<td/>').html(
                (function() {
                    return m.catalog ? m.catalog.name : '';
                })()
            ).appendTo(row);
            $('<td/>')
                .append(
                    $('<button type="button" class="btn btn-warning btn-xs">修改</button>')
                        .click(function(e) {
                            var m = $(this).closest('tr').data('value');
                            MPDialog.tagAppend({
                                data: m,
                                confirmCallback: function() {
                                    tagViewList();
                                }
                            });
                        })
                )
                .append(
                    $('<button type="button" class="btn btn-danger btn-xs">删除</button>')
                        .click(function(e) {
                            var m = $(this).closest('tr').data('value');
                            MPDialog.confirm({
                                message: '确认删除?',
                                confirmCallback: function() {
                                    if (App.getLang() == 'zhCN') {
                                        var parameter = {
                                            siteId: App.getSiteId(),
                                            lang: App.getLang(),
                                            tagcatId: m.catalog.id,
                                            id: m.id
                                        };
                                        Apis.getTagLangAll(parameter, function(response) {
                                            var list = response.data;
                                            var id = [];
                                            list.forEach(function(m) {
                                                id.push(m.id);
                                            });
                                            var parameter = {
                                                id: id
                                            };
                                            Apis.delTagLangAll(parameter, function() {
                                                tagViewList();
                                            });
                                        });
                                        return;
                                    }
                                    Apis.delTag({id: m.id}, function() {
                                        tagViewList();
                                    });
                                }
                            });
                        })
                )
                .appendTo(row);
        });
    };

    var siteId = App.getSiteId();
    var condition = formValue($('form', panelElement));
    condition.lang = App.getLang();
    condition.siteId = siteId;
    condition.start = 0;
    condition.size = 99999;
    Apis.getTags(condition, function(response) {
        build(response);
    });

    var select = $('[name="catalogId"]', panelElement);
    selectOptionsForTagCatLog(siteId, select);

}

// 标签分类下拉框
function selectOptionsForTagCatLog(siteId, selectElement, callback) {

    var selectList = [
        $('.mp-panel-tag [name="catalogId"]'),
        $('.mp-panel-append-tag [name="catalogId"]')
    ];

    if (selectElement) {
        selectList = [selectElement];
    }

    // 检索条件
    var condition = {};
    condition.lang = App.getLang();
    condition.siteId = siteId;
    condition.start = 0;
    condition.size = 99999;
    Apis.getTagCategotys(condition, function(response) {
        var list = response.data.catalogs;
        selectList.forEach(function(select) {
            select.empty();
            select.append('<option value="">请选择</option>');
            list.forEach(function(m) {
                select.append(
                    $('<option/>').attr('value', m.id).html(m.name)
                );
            });
        });
        callback && callback();
    });

}

// 显示邮箱设置
function emailSettingsView() {

    var panelElement = $('.mp-panel-email-settings');

    MPDialog.openWaiting();
    var build = function(response) {
        setTimeout(function() {
            MPDialog.closeWaiting();
        }, 1000);

        var settings = response.data;
        if (settings) {
            $('[name="id"]', panelElement).val(settings.id);
            $('[name="stmp"]', panelElement).val(settings.smtp);
            $('[name="port"]', panelElement).val(settings.port);
            $('[name="sender"]', panelElement).val(settings.sender);
            $('[name="password"]', panelElement).val(settings.senderPasword);
            $('[name="recievers"]', panelElement).val(settings.recievers.join(','));
        }
    };

    var siteId = App.getSiteId();
    Apis.getEmailSettings(siteId, function(response) {
        build(response);
    });

    var submitForm = function(callback) {
        MPDialog.openWaiting();
        var siteId = App.getSiteId();
        var condition = formValue($('form', panelElement));
        condition.siteId = siteId;
        Apis.updEmailSettings(condition, function(response) {
            callback();
        });
    };

    $('.btn-test', panelElement).unbind().click(function() {
        MPDialog.openWaiting();
        submitForm(function() {
            var siteId = App.getSiteId();
            Apis.testEmailSettings(siteId, function(response) {
                setTimeout(function() {
                    MPDialog.closeWaiting();
                }, 1000);
            });
        })
    });

    $('.btn-submit', panelElement).unbind().click(function() {
        MPDialog.openWaiting();
        submitForm(function() {
            setTimeout(function() {
                MPDialog.closeWaiting();
            }, 1000);
        })
    });

}

/** **************************************************************************************************** 文章 */

// 显示文章列表
function articleViewList(pageIndex) {

    var panelElement = $('.mp-panel-article-list');
    var listContianer = $('table tbody', panelElement).empty();

    var userInfo = App.getUserInfo();

    MPDialog.openWaiting();
    var build = function(response) {
        setTimeout(function() {
            MPDialog.closeWaiting();
        }, 1000);

        var list = response.data ? response.data.articles : [];
        listContianer.empty();

        if (!list || list.length == 0) {
            return;
        }

        list.forEach(function(m) {
            var row = $('<tr/>').appendTo(listContianer);
            row.data('value', m);
            $('<td class="t-checkbox"/>').html((function() {
                return '<input type="checkbox" class="t-checkbox-item" />';
            })()).appendTo(row);
            $('<td/>').html(m.articleNo).appendTo(row);
            $('<td/>').html(m.title).appendTo(row);
            // $('<td/>').html((function() {
            //     if (m.canModify == 0) {
            //         return '<span style="color: red;">禁止修改</span>';
            //     }
            //     return '<span style="color: green;">允许修改</span>';
            // })()).appendTo(row);
            $('<td/>').html(m.updateBy ? m.updateBy : m.creator).appendTo(row);
            $('<td/>').html((function() {
                var v = m.updateAt;
                if (v) {
                    return moment(v).format('YYYY-MM-DD HH:mm');
                }
                return '';
            })()).appendTo(row);

            var optsTd = $('<td/>').appendTo(row);
            optsTd.append(
                $('<button type="button" class="btn btn-warning btn-xs">修改</button>')
                    .click(function(e) {
                        var m = $(this).closest('tr').data('value');
                        // 还原编辑面板
                        $('.mp-panel-article-edit [data-post-panel-class]').removeClass('active');
                        $('.mp-panel-article-edit [data-post-panel-class="mp-post-attribute"]').addClass('active');
                        $('.mp-panel-article-edit form').removeClass('mp-panel-visible');
                        $('.mp-panel-article-edit form.mp-post-attribute').addClass('mp-panel-visible');
                        intoArticleUpdateMode(m.id);

                        $('html,body').animate({scrollTop: 0}, 200);
                    })
            );
            optsTd.append(
                $('<button type="button" class="btn btn-danger btn-xs">删除</button>')
                    .click(function(e) {
                        var m = $(this).closest('tr').data('value');
                        MPDialog.confirm({
                            message: '确认删除?',
                            confirmCallback: function() {
                                Apis.deleteArticle({id: m.id}, function() {
                                    articleViewList(pageIndex);
                                });
                            }
                        });
                    })
            );
            // if (userInfo.role != 3 && (userInfo.role == 1 || m.canModify == 1)) {
            //     optsTd.append(
            //         $('<button type="button" class="btn btn-warning btn-xs">修改</button>')
            //             .click(function(e) {
            //                 var m = $(this).closest('tr').data('value');
            //                 // 还原编辑面板
            //                 $('.mp-panel-article-edit [data-post-panel-class]').removeClass('active');
            //                 $('.mp-panel-article-edit [data-post-panel-class="mp-post-attribute"]').addClass('active');
            //                 $('.mp-panel-article-edit form').removeClass('mp-panel-visible');
            //                 $('.mp-panel-article-edit form.mp-post-attribute').addClass('mp-panel-visible');
            //                 intoArticleUpdateMode(m.id);
            //
            //                 $('html,body').animate({scrollTop: 0}, 200);
            //             })
            //     );
            // }
            // optsTd.append(
            //     $('<button type="button" class="btn btn-success btn-xs">预览</button>')
            //         .click(function(e) {
            //             var m = $(this).closest('tr').data('value');
            //             // window.open('preview/mockup/book.html?id=' + m.id, '_blank');
            //             window.open('../manual/article.html?siteId=' + App.getSiteId() + '&lang=' + App.getLang() + '&articleId=' + m.id, '_blank');
            //         })
            // );
            // if (userInfo.role == 1) {
            //     optsTd.append(
            //         $('<button type="button" class="btn btn-danger btn-xs">删除</button>')
            //             .click(function(e) {
            //                 var m = $(this).closest('tr').data('value');
            //                 MPDialog.confirm({
            //                     message: '确认删除?',
            //                     confirmCallback: function() {
            //                         Apis.deleteArticle({id: m.id}, function() {
            //                             articleViewList(pageIndex);
            //                         });
            //                     }
            //                 });
            //             })
            //     );
            // }
        });

        var currLang = App.getLang();
        if (currLang == 'zhCN') {
            $('.lang-zhCN', panelElement).show();
        } else {
            $('.lang-zhCN', panelElement).hide();
        }

        // 同步功能
        if (currLang == 'zhCN' && userInfo.role == 1) {
            $('[data-role="1"]').show();
        } else {
            $('[data-role="1"]').hide();
        }

        $('.t-checkbox-item', panelElement).unbind().change(function() {
            if (!this.checked) {
                $('.t-checkbox-all', panelElement)[0].checked = false;
            }
        });
    };

    var pageSize = 10;

    var siteId = App.getSiteId();
    var condition = formValue($('form', panelElement));
    condition.articleNo = condition.articleNo ? condition.articleNo : null;
    condition.title = condition.title ? condition.title : null;
    condition.userId = condition.userId ? condition.userId : null;
    condition.canModify = condition.canModify ? condition.canModify : -1;
    condition.lang = App.getLang();
    condition.siteId = siteId;
    condition.pageSize = pageSize;
    condition.pageStart = pageIndex ? (pageIndex * pageSize) : 0;
    condition.detail = false;
    Apis.getArticleList(condition, function(response) {
        build(response);
        var page = Pagination({
            pageStart: pageIndex,
            pageSize: condition.pageSize,
            totalSize: response.data.totalSize
        }, function(index) {
            articleViewList(index);
        });
        $('.pagination', panelElement).parent().empty()
            .append(page);
    });

    var sortArticleNo = $('.mp-sort-by-article_no', panelElement);
    var sortUpdateAt = $('.mp-sort-by-update_at', panelElement);
    sortArticleNo.unbind().click(function() {
        sortUpdateAt.removeClass('mp-sort-selected').find('.iconfont').remove();
        sortArticleNo.addClass('mp-sort-selected').find('.iconfont').remove();
        var ascOrDes = sortArticleNo.data('order');
        if (ascOrDes == 'desc') {
            ascOrDes = true;
            sortArticleNo.attr('order', 'asc');
            sortArticleNo.data('order', 'asc');
            sortArticleNo.append('<i class="icon iconfont"></i>');
            $('.iconfont', sortArticleNo).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-shengxu');
        } else {
            ascOrDes = false;
            sortArticleNo.attr('order', 'desc');
            sortArticleNo.data('order', 'desc');
            sortArticleNo.append('<i class="icon iconfont"></i>');
            $('.iconfont', sortArticleNo).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-jiangxu');
        }
        var orders = [
            {
                field: 'a.article_no',
                ascOrDes: ascOrDes
            }
        ];

        var siteId = App.getSiteId();
        var condition = formValue($('form', panelElement));
        condition.articleNo = condition.articleNo ? condition.articleNo : null;
        condition.title = condition.title ? condition.title : null;
        condition.userId = condition.userId ? condition.userId : null;
        condition.canModify = condition.canModify ? condition.canModify : -1;
        condition.lang = App.getLang();
        condition.siteId = siteId;
        condition.pageSize = pageSize;
        condition.pageStart = pageIndex ? (pageIndex * pageSize) : 0;
        condition.detail = false;
        condition.orders = orders;
        Apis.getArticleList(condition, function(response) {
            build(response);
            var page = Pagination({
                pageStart: pageIndex,
                pageSize: condition.pageSize,
                totalSize: response.data.totalSize
            }, function(index) {
                articleViewList(index);
            });
            $('.pagination', panelElement).parent().empty()
                .append(page);
        });
    });
    sortUpdateAt.unbind().click(function() {
        sortUpdateAt.addClass('mp-sort-selected').find('.iconfont').remove();
        sortArticleNo.removeClass('mp-sort-selected').find('.iconfont').remove();
        var ascOrDes = sortUpdateAt.data('order');
        if (ascOrDes == 'desc') {
            ascOrDes = true;
            sortUpdateAt.attr('order', 'asc');
            sortUpdateAt.data('order', 'asc');
            sortUpdateAt.append('<i class="icon iconfont"></i>');
            $('.iconfont', sortUpdateAt).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-shengxu');
        } else {
            ascOrDes = false;
            sortUpdateAt.attr('order', 'desc');
            sortUpdateAt.data('order', 'desc');
            sortUpdateAt.append('<i class="icon iconfont"></i>');
            $('.iconfont', sortUpdateAt).removeClass('icon-paixu-jiangxu icon-paixu-shengxu').addClass('icon-paixu-jiangxu');
        }
        var orders = [
            {
                field: 'a.update_at',
                ascOrDes: ascOrDes
            }
        ];

        var siteId = App.getSiteId();
        var condition = formValue($('form', panelElement));
        condition.articleNo = condition.articleNo ? condition.articleNo : null;
        condition.title = condition.title ? condition.title : null;
        condition.userId = condition.userId ? condition.userId : null;
        condition.canModify = condition.canModify ? condition.canModify : -1;
        condition.lang = App.getLang();
        condition.siteId = siteId;
        condition.pageSize = pageSize;
        condition.pageStart = pageIndex ? (pageIndex * pageSize) : 0;
        condition.detail = false;
        condition.orders = orders;
        Apis.getArticleList(condition, function(response) {
            build(response);
            var page = Pagination({
                pageStart: pageIndex,
                pageSize: condition.pageSize,
                totalSize: response.data.totalSize
            }, function(index) {
                articleViewList(index);
            });
            $('.pagination', panelElement).parent().empty()
                .append(page);
        });
    });

    // 选择全部
    $('.t-checkbox-all', panelElement).unbind().change(function() {
        if (this.checked) {
            $('.t-checkbox-item', panelElement).each(function(i, checkbox) {
                checkbox.checked = true;
            });
        } else {
            $('.t-checkbox-item', panelElement).each(function(i, checkbox) {
                checkbox.checked = false;
            });
        }
    });

    // 同步
    var sync = function(syncType) {
        var parameter = {
            siteId: App.getSiteId(),
            syncType: syncType,
            selectItems: (function() {
                var selectItems = [];
                $('.t-sync-checked [type="checkbox"]', panelElement).each(function(i, checkbox) {
                    if (checkbox.checked) {
                        selectItems.push(checkbox.value);
                    }
                });
                return selectItems;
            })(),
            cnSelectArticleNos: (function() {
                if (syncType == 1) {
                    return {};
                }
                var cnSelectArticleNos = {};
                $('.t-checkbox-item', panelElement).each(function(i, checkbox) {
                    if (checkbox.checked) {
                        var m = $(checkbox).closest('tr').data('value');
                        cnSelectArticleNos[m.articleNo] = m.id;
                    }
                });
                return cnSelectArticleNos;
            })()
        };

        if (parameter.selectItems.length == 0) {
            MPDialog.alert({
                message: '请勾选同步内容'
            });
            return;
        }

        if (syncType == 0) {
            var count = 0;
            for (var k in parameter.cnSelectArticleNos) {
                count ++;
            }
            if (count == 0) {
                MPDialog.alert({
                    message: '请勾选文章'
                });
                return;
            }
        }

        MPDialog.confirm({
            message: syncType == 0 ? '确认同步勾选？' : '确认同步全部？',
            confirmCallback: function() {
                Apis.sync(parameter, function(response) {
                    if (response.status == 200) {
                        MPDialog.alert({
                            message: '同步完成'
                        });
                    } else {
                        MPDialog.alert({
                            message: '同步异常：' + response.message
                        });
                    }
                });
            }
        });
    };

    // 同步勾选
    $('.t-sync-select',panelElement).unbind().click(function() {
        sync(0);
    });

    // 同步全部
    $('.t-sync-all', panelElement).unbind().click(function() {
        sync(1);
    });

    var getCheckedIds = function() {
        var list = [];
        $('.t-checkbox-item', panelElement).each(function(i, checkbox) {
            if (checkbox.checked) {
                var m = $(checkbox).closest('tr').data('value');
                list.push(m.id);
            }
        });
        return list;
    }

    var setCanModify = function(canModify) {
        var parameter = {
            articleIds: getCheckedIds(),
            canModify: canModify
        };

        if (parameter.articleIds.length == 0) {
            MPDialog.alert({
                message: '请勾选文章'
            });
            return;
        }

        MPDialog.confirm({
            message: canModify == 1 ? '确认开放修改？' : '确认关闭修改？',
            confirmCallback: function() {
                Apis.setCanModify(parameter, function(response) {
                    articleViewList(pageIndex);
                    MPDialog.alert({
                        message: '操作完成'
                    });
                });
            }
        });
    };

    $('.t-can-modify-yes', panelElement).unbind().click(function() {
        setCanModify(1);
    });

    $('.t-can-modify-no', panelElement).unbind().click(function() {
        setCanModify(0);
    });

    if (userInfo.role == 1 && App.getLang() == 'zhCN') {
        $('.t-can-modify-yes', panelElement).show();
        $('.t-can-modify-no', panelElement).show();
    } else {
        $('.t-can-modify-yes', panelElement).hide();
        $('.t-can-modify-no', panelElement).hide();
    }
}

/** *************************** 文章编辑 begin */

var CurrUEditor = null;

// 面板按钮
function initPostPanelToolsbar() {
    // enableScrollListener();
    // setScrollListener('mp-panel-forms-content-toolsbar', function(jWindow) {
    //     var panel = $('.mp-panel-article-edit ');
    //     var spyBody = $('.mp-panel-forms-content', panel);
    //     var spyFixed = $('.mp-toolsbar .mp-fixed', panel);
    //     var position = spyBody.offset();
    //     var wTop = jWindow.scrollTop();
    //     if (wTop > position.top) {
    //         spyFixed.css({
    //             position: 'absolute',
    //             top: 95 + 'px'
    //         });
    //     } else {
    //         spyFixed.css({
    //             position: 'relative',
    //         });
    //     }
    // });


    function OnScroll(jWindow) {
        // var spyBody = $('#mp-post-summary-editor-container', panel);
        var spyFixed = $('.mp-panel-article-edit .mp-toolsbar-row');
        // var position = spyBody.offset();
        var position = {top: 100};
        var wTop = jWindow.scrollTop();
        if (wTop > position.top) {
            spyFixed.css({
                position: 'absolute',
                top: (wTop) + 'px'
            });
        } else {
            spyFixed.css({
                position: 'absolute',
                top: (wTop) + 'px'
            });
        }
    }
    enableScrollListener();
    setScrollListener('mp-post-scroll', function(jWindow) {
        OnScroll(jWindow);
    });
    OnScroll($(window));
    $('.mp-panel-article-edit .mp-toolsbar-row .mp-insert-image').unbind().click(function() {
        MPDialog.selectImageMaterial({
            cache: 'apply',
            siteId: App.getSiteId(),
            lang: App.getLang(),
            confirmCallback: function(list) {
                console.log('selected:', list);
                if (!CurrUEditor) {
                    return;
                }
                list.forEach(function(data) {
                    CurrUEditor
                        .execCommand( 'inserthtml',
                            '<p><img src="{0}"></p>'.format(data.url)
                        );
                });
            }
        });
    });
}

// 编辑文章
function intoArticleUpdateMode(articleId) {
    Apis.getArticle({id: articleId}, function(response) {
        var m = response.data;
        var firstPanelElement = $('.mp-panel-article-list');
        var secondPanelElement = $('.mp-panel-article-edit');
        eventNavigationForwordNow(firstPanelElement, secondPanelElement,
            function(firstPanelElement, secondPanelElement) {
                var saveArticle = function(finishCallback) {
                    var data = formValueForArticle();
                    var checkResult = vaildateForArticle(data);
                    if (!checkResult.result) {
                        $('.mp-danger-alert-message').html(checkResult.message).closest('.row').show();
                        return false;
                    } else {
                        $('.mp-danger-alert-message').closest('.row').hide();
                    }
                    data.siteId = App.getSiteId();
                    data.lang = App.getLang();
                    if (data.id) {
                        // TODO update
                        Apis.updateArticle(data, function(response) {
                            finishCallback && finishCallback();
                            $('.mp-success-alert-message').html('已保存').closest('.row').show();
                            $('.mp-panel-article-edit .mp-post-info [name="id"]').val(response.data);
                            MPDialog.alert({
                                message: '已保存'
                            });
                            intoArticleUpdateMode(response.data);
                            articleViewList();
                        });
                    } else {
                        // TODO create
                        Apis.createArticle(data, function(response) {
                            finishCallback && finishCallback();
                            $('.mp-success-alert-message').html('已保存').closest('.row').show();
                            $('.mp-panel-article-edit .mp-post-info [name="id"]').val(response.data);
                            MPDialog.alert({
                                message: '已保存'
                            });
                            intoArticleUpdateMode(response.data);
                            articleViewList();
                        });
                    }
                    return false;
                };
                eventNavigationSubmit(firstPanelElement, secondPanelElement, function() {
                    saveArticle();
                    return false;
                });
                eventNavigationCancel(firstPanelElement, secondPanelElement, function() {
                    articleViewList();
                    $('.mp-panel-article-edit-title').hide();
                    removeScrollListener('mp-post-attr');
                    removeScrollListener('mp-post-attr-title');
                });

                // 设置面板标题
                $('.mp-panel-title a', secondPanelElement).html('修改文章');

                // 预览
                $('.mp-preview', secondPanelElement).show().unbind().click(function() {
                    // window.open('preview/mockup/book.html?id=' + m.id, '_blank');
                    window.open('../manual/article.html?siteId=' + App.getSiteId() + '&lang=' + App.getLang() + '&articleId=' + m.id, '_blank');
                });

                // 记录面板状态
                var originalPostPanelClass = $('.mp-panel-article-edit [data-post-panel-class].active').data('postPanelClass');

                // 还原编辑面板
                // $('.mp-panel-article-edit [data-post-panel-class]').removeClass('active');
                // $('.mp-panel-article-edit [data-post-panel-class="mp-post-attribute"]').addClass('active');
                // $('.mp-panel-article-edit form').removeClass('mp-panel-visible');
                // $('.mp-panel-article-edit form.mp-post-attribute').addClass('mp-panel-visible');
                initPostBefore();

                // 设置数据到UI
                var data = m;

                var flow2OpSamplesList = data.flowDescription
                    .sort(function(a, b) {
                        return a.index - b.index;
                    })
                    .map(function(m) {
                        var flow = {uuid: uuid(), flowId: m.id, flow: m.tilte, opSampleId: 0, opSamples: ''};
                        var opSamples = m.opSamples ? m.opSamples[0] : null;
                        if (opSamples) {
                            flow.opSampleId = opSamples.id;
                            flow.opSamples = opSamples.content;
                            flow.tips = opSamples.tips;
                            flow.tipsColor = opSamples.tipsColor;
                        }
                        return flow;
                    });

                // data.summary = '<p>123</p>';
                // flow2OpSamplesList = [
                //     {uuid: uuid(), flowId: 1, flow: '测试流程简述1', opSampleId: 1, opSamples: '<p>测试操作规范1</p>'},
                //     {uuid: uuid(), flowId: 2, flow: '测试流程简述2', opSampleId: 2, opSamples: '<p>测试操作规范2</p>'}
                // ];
                // data.relatedArticle = [
                //     {
                //         relateArticleId: 1,
                //         relateArticleTitle: '安装手册'
                //     }
                // ];
                // data.relatedVideo = [
                //     {
                //         id: 1,
                //         videoUrl: ''
                //     }
                // ];
                // data.tags = [
                //     {"tagId":1,"tagcatId":1},
                //     {"tagId":4,"tagcatId":2,"tag":null,"lang":"zhCN"},
                //     {"tagId":10,"tagcatId":12}
                // ];

                // 全部初始化
                {
                    $('.mp-panel-article-edit [data-post-panel-class]').each(function(i, tab) {
                        var targetPanelClass = $(tab).data('postPanelClass');
                        var targetPanel = $('.mp-panel-article-edit .' + targetPanelClass);
                        targetPanel.addClass('mp-panel-visible');
                        if (targetPanelClass == 'mp-post-step-standard') {
                            return;
                        }
                        targetPanel.addClass('mp-panel-init');
                    });

                    // 文章属性
                    initPostAttribute(data);
                    // 摘要
                    initPostSummary(data);
                    // 流程简述
                    initPostProcessStep(flow2OpSamplesList);
                    // 操作范例
                    // targetPanel.addClass('mp-panel-init');
                    if (!$('.mp-panel-article-edit .mp-post-step-standard').hasClass('mp-panel-init-first')) {
                        $('.mp-panel-article-edit .mp-post-step-standard').addClass('mp-panel-init-first');
                        initPostStepStandardForUpdate(flow2OpSamplesList);
                        initPostStepStandard();
                    } else {
                        initPostStepStandard();
                    }
                    // 图片
                    initPostImage(data.articleImage);
                    // 视频
                    initPostVideo(data.articleVideo);
                    // 备注
                    initPostRemark(data);
                    // 相关文章
                    initPostRelatedPost(data.relatedArticle);
                    // 相关视频
                    initPostRelatedVideo(data.relatedVideo);
                    // 标签
                    initPostTag(data);

                    // 还原编辑面板
                    $('.mp-panel-article-edit [data-post-panel-class]').removeClass('active');
                    $('.mp-panel-article-edit [data-post-panel-class="' + originalPostPanelClass + '"]').addClass('active');
                    $('.mp-panel-article-edit form').removeClass('mp-panel-visible');
                    $('.mp-panel-article-edit form.' + originalPostPanelClass).addClass('mp-panel-visible');
                }

                // 文章编辑.面板切换
                $('.mp-panel-article-edit [data-post-panel-class]').each(function(i, el) {
                    $(el).unbind().click(function(e) {
                        // 菜单
                        $('.mp-panel-article-edit [data-post-panel-class]').removeClass('active');
                        $(this).addClass('active');
                        // 面板
                        $('.mp-panel-article-edit form').removeClass('mp-panel-visible');
                        var targetPanelClass = $(this).data('postPanelClass');
                        var targetPanel = $('.mp-panel-article-edit .' + targetPanelClass);
                        targetPanel.addClass('mp-panel-visible');
                        switch (targetPanelClass) {
                            case 'mp-post-summary': // 摘要
                            case 'mp-post-step-standard': // 操作范例
                            case 'mp-post-remark': // 备注
                            default:
                                CurrUEditor = null;
                        }
                        if (targetPanel.hasClass('mp-panel-init')) {
                            return;
                        }
                        switch (targetPanelClass) {
                            case 'mp-post-attribute':
                                // 文章属性
                                targetPanel.addClass('mp-panel-init');
                                initPostAttribute(data);
                                break;

                            case 'mp-post-summary':
                                // 摘要
                                targetPanel.addClass('mp-panel-init');
                                initPostSummary(data);
                                break;

                            case 'mp-post-process-step':
                                // 流程简述
                                targetPanel.addClass('mp-panel-init');
                                initPostProcessStep(flow2OpSamplesList);
                                break;

                            case 'mp-post-step-standard':
                                // 操作范例
                                // targetPanel.addClass('mp-panel-init');
                                if (!targetPanel.hasClass('mp-panel-init-first')) {
                                    targetPanel.addClass('mp-panel-init-first');
                                    initPostStepStandardForUpdate(flow2OpSamplesList);
                                    initPostStepStandard();
                                } else {
                                    initPostStepStandard();
                                }
                                break;

                            case 'mp-post-image':
                                // 图片
                                targetPanel.addClass('mp-panel-init');
                                initPostImage(data.articleImage);
                                break;

                            case 'mp-post-video':
                                // 视频
                                targetPanel.addClass('mp-panel-init');
                                initPostVideo(data.articleVideo);
                                break;

                            case 'mp-post-remark':
                                // 备注
                                targetPanel.addClass('mp-panel-init');
                                initPostRemark(data);
                                break;

                            case 'mp-post-related-post':
                                // 相关文章
                                targetPanel.addClass('mp-panel-init');
                                initPostRelatedPost(data.relatedArticle);
                                break;

                            case 'mp-post-related-video':
                                // 相关视频
                                targetPanel.addClass('mp-panel-init');
                                initPostRelatedVideo(data.relatedVideo);
                                break;

                            case 'mp-post-tag':
                                // 标签
                                targetPanel.addClass('mp-panel-init');
                                initPostTag(data);
                                break;
                            default:
                        }
                    });
                });
                // $('.mp-panel-article-edit [data-post-panel-class]:first').trigger("click");

                initPostPanelToolsbar();
            });
    });
}

// 清空UI
function initPostBefore() {

    MPDialogCache.selectImageMaterial = null;
    MPDialogCache.selectVideoMaterial = null;

    // 消息
    $('.mp-success-alert-message').html('').closest('.row').hide();
    $('.mp-danger-alert-message').html('').closest('.row').hide();

    // 文章属性
    var form = $('.mp-panel-article-edit form.mp-post-info');
    $('[name="id"]', form).val('');
    var form = $('.mp-panel-article-edit form.mp-post-attribute');
    $('[name="articleNo"]', form).val('');
    $('[name="fileName"]', form).val('');
    $('[name="title"]', form).val('');

    // 摘要
    if (SummaryMPEditor) {
        SummaryMPEditorValueCache = null;
        SummaryMPEditor.destroy();
        SummaryMPEditor = null;
    }
    $('.mp-panel-article-edit .mp-post-summary .mp-editor').empty();

    // 流程简述
    $('.mp-panel-article-edit .mp-post-process-step table tbody').empty();

    // 操作范例
    MPEditorList && MPEditorList.forEach(function(mpEditor) {
        var cache = mpEditor.getCache();
        MPEditorValueCache[cache.id] = cache.content;
        mpEditor.destroy();
    });
    MPEditorValueCache = {};
    MPEditorList = [];
    $('.mp-panel-article-edit .mp-post-step-standard .mp-editor-list').empty();

    // 备注
    RemarkMPEditor && RemarkMPEditor.destroy();
    RemarkMPEditorValueCache = null;
    RemarkMPEditor = null;
    $('.mp-panel-article-edit .mp-post-remark .mp-editor').empty();

    // 图片
    $('.mp-panel-article-edit .mp-post-image .mp-image-list').empty();

    // 视频
    $('.mp-panel-article-edit .mp-post-video .mp-video-list').empty();

    // 相关文章
    $('.mp-panel-article-edit .mp-post-related-post table tbody').empty();

    // 相关视频
    $('.mp-panel-article-edit .mp-post-related-video .mp-video-list').empty();

    // 标签
    $('.mp-panel-article-edit .mp-post-tag .mp-tag-category').empty();

    $('.mp-panel-article-edit .mp-panel-init-first').removeClass('mp-panel-init-first');
    $('.mp-panel-article-edit .mp-panel-init').removeClass('mp-panel-init');

}

// 文章属性
function initPostAttribute(data) {
    var form = $('.mp-panel-article-edit form.mp-post-attribute');
    // 修改模式
    if (data) {
        $('[name="articleNo"]', form).val(data.articleNo);
        $('[name="fileName"]', form).val(data.fileName);
        $('[name="title"]', form).val(data.title);

        if (data.id) {
            var form = $('.mp-panel-article-edit form.mp-post-info');
            $('[name="id"]', form).val(data.id);
        }
    }


    var panel = $('.mp-panel-article-edit');
    $('[name="articleNo"]', panel).change(function() {
        var articleNoValueOriginal = $(this).data('original');
        var articleNoValue = $(this).val();
        var fileNameInput = $('[name="fileName"]', form);
        var fileNameValue = fileNameInput.val();
        if (!fileNameValue || fileNameValue.trim() == '' || fileNameValue == articleNoValueOriginal) {
            fileNameInput.val(articleNoValue + '.html');
        }
        $(this).data('original', articleNoValue + '.html');
        var title = ''
            .concat($('[name="articleNo"]', panel).val())
            .concat(' ')
            .concat($('[name="title"]', panel).val());
        $('.mp-panel-title a', panel).html(title);
    });
    $('[name="title"]', panel).change(function() {
        var panel = $('.mp-panel-article-edit');
        var title = ''
            .concat($('[name="articleNo"]', panel).val())
            .concat(' ')
            .concat($('[name="title"]', panel).val());
        $('.mp-panel-title a', panel).html(title);
    }).change();

    enableScrollListener();
    setScrollListener('mp-post-attr-title', function(jWindow) {
        var spyBody = $('.mp-panel-article-edit');
        var position = spyBody.offset();
        var wTop = jWindow.scrollTop();
        if (wTop >= position.top) {
            // show
            var refPanel = $('.mp-panel-article-edit');
            var titlePanel = $('.mp-panel-article-edit-title');
            titlePanel.css({
                left: refPanel.offset().left,
                width: refPanel.width() + 36
            });
            if (titlePanel.is(':hidden')) {
                titlePanel.show();
            }
            var form = $('.mp-panel-article-edit form.mp-post-attribute');
            var title = ''
                .concat($('[name="articleNo"]', form).val())
                .concat(' ')
                .concat($('[name="title"]', form).val());
            $('.mp-panel-title a', titlePanel).html(title);
        } else {
            // hide
            var titlePanel = $('.mp-panel-article-edit-title');
            if (!titlePanel.is(':hidden')) {
                titlePanel.hide();
            }
        }
    });
}

// 摘要
var SummaryMPEditorValueCache = null;
var SummaryMPEditor = null;
function initPostSummary(data) {
    if (SummaryMPEditor) {
        SummaryMPEditorValueCache = SummaryMPEditor.getCache();
        SummaryMPEditor.destroy();
    }

    var panel = $('.mp-panel-article-edit .mp-post-summary');
    var editorContainer = $('.mp-editor', panel).empty();

    var mpEditor = new MPEditor({
        id: 'mp-post-summary-editor-container',
        content: (function() {
            return data ? data.summary : '<p></p>';
        })(),
        onSelectionChangeEvent: function(ueEditor) {
            CurrUEditor = ueEditor;
        }
    });
    mpEditor.element().appendTo(editorContainer);
    var ueEditor = mpEditor.init();
    SummaryMPEditor = mpEditor;

    // $('.mp-insert-image', panel).unbind().click(function() {
    //     MPDialog.selectImageMaterial({
    //         cache: 'apply',
    //         siteId: App.getSiteId(),
    //         lang: App.getLang(),
    //         confirmCallback: function(list) {
    //             console.log('selected:', list);
    //             list.forEach(function(data) {
    //                 CurrUEditor
    //                     .execCommand( 'inserthtml',
    //                         '<p><img src="{0}"></p>'.format(data.url)
    //                     );
    //             });
    //         }
    //     });
    // });

}

// 流程简述
function initPostProcessStep(flow2OpSamplesList) {
    var panel = $('.mp-panel-article-edit .mp-post-process-step');
    var tbody = $('table tbody', panel).empty();
    var append = function(m) {
        var row = $('<tr/>').appendTo(tbody);
        $('<td class="mp-move-sort"/>').html('<i class="icon iconfont icon-move"></i>').appendTo(row);
        $('<td/>').html((function() {
            var input = $('<input type="text" class="form-control" name="flow" value=""/>');
            var value = depthValue(m, 'flow', '');
            if (value)
                input.val(value);
            return input;
        })()).appendTo(row);
        $('<td/>').html((function() {
            var div = $('<div/>');
            var _uuid = m ? m.uuid : uuid();
            div.append(
                $('<input type="hidden" name="uuid">').val(_uuid)
            );
            div.append(
                $('<input type="hidden" name="flowId">').attr('data-uuid', _uuid)
                    .val((function() {
                        return depthValue(m, 'flowId', '0');
                    })())
            );
            div.append(
                $('<input type="hidden" name="opSampleId">')
                    .val((function() {
                        return depthValue(m, 'opSampleId', '0');
                    })())
            );
            div.append(
                $('<button type="button" class="btn btn-danger btn-xs">删除</button>')
                    .click(function(e) {
                        $(e.target).closest('tr').remove();
                        var _uuid = $(e.target).closest('td').find('[name="uuid"]').val();
                        (function() {
                            var list = [];
                            MPEditorList.forEach(function(mpEditor) {
                                var opts = mpEditor.getOpts();
                                if (opts.id == _uuid) {
                                    var cache = mpEditor.getCache();
                                    MPEditorValueCache[cache.id] = cache.content;
                                    mpEditor.destroy();
                                    return;
                                }
                                list.push(mpEditor);
                            });
                            MPEditorList = list;
                        })();
                        (function() {
                            var list = [];
                            TipsMPEditorList.forEach(function(mpEditor) {
                                var opts = mpEditor.getOpts();
                                if (opts.id == _uuid) {
                                    var cache = mpEditor.getCache();
                                    TipsMPEditorValueCache[cache.id] = cache.content;
                                    mpEditor.destroy();
                                    return;
                                }
                                list.push(mpEditor);
                            });
                            TipsMPEditorList = list;
                        })();
                    })
            );
            return div;
        })()).appendTo(row);
    };
    flow2OpSamplesList && flow2OpSamplesList
        .forEach(function(m) {
            append(m);
        });

    // 添加
    $('.mp-append', panel).unbind().click(function() {
        append();
        // 刷新操作范例
        initPostStepStandard();
    });

    // 拖动排序
    $(".mp-post-process-step table tbody").sortable({
        helper: function(e, tr) {
            var $originals = tr.children();
            var $helper = tr.clone();
            $helper.children().each(function(index) {
                $(this).width($originals.eq(index).width())
            });
            return $helper;
        },
        stop: function(e, ui) {
        }
    }).disableSelection();

}

// 操作范例
var MPEditorValueCache = {};
var MPEditorList = [];
var TipsMPEditorValueCache = {};
var TipsMPEditorList = [];
function initPostStepStandardForUpdate(flow2OpSamplesList) {
    flow2OpSamplesList.forEach(function(m, idx) {
        MPEditorValueCache[m.uuid] = m.opSamples;
        TipsMPEditorValueCache[m.uuid] = {tips: m.tips, tipsColor: m.tipsColor};
    });
}
function initPostStepStandard() {

    var panel = $('.mp-panel-article-edit .mp-post-step-standard');
    $('.mp-editor-list', panel).empty();

    var flowUuidList = [];
    $('.mp-panel-article-edit .mp-post-process-step input[name="uuid"]')
        .each(function(i, input) {
            flowUuidList.push(input.value);
        });
    if (flowUuidList.length == 0 && MPEditorList.length == 0) {
        return;
    }
    var flowTitleList = [];
    $('.mp-panel-article-edit .mp-post-process-step input[name="flow"]')
        .each(function(i, input) {
            flowTitleList.push(input.value);
        });

    MPEditorList.forEach(function(mpEditor) {
        try {
            var cache = mpEditor.getCache();
            MPEditorValueCache[cache.id] = cache.content;
            mpEditor.destroy();
        } catch (e) {

        }
    });
    MPEditorList = [];
    TipsMPEditorList.forEach(function(mpEditor) {
        try {
            var cache = mpEditor.getCache();
            TipsMPEditorValueCache[cache.id + '-tips'] = cache.content;
            mpEditor.destroy();
        } catch (e) {

        }
    });
    TipsMPEditorList = [];

    if (flowUuidList.length === 0) {
        return;
    }

    var editorContainer = $('.mp-editor-list', panel);

    flowUuidList.forEach(function(_uuid, idx) {
        if (idx > 0) {
            $('<hr>').appendTo(editorContainer);
        }
        // body
        (function() {
            var content = MPEditorValueCache[_uuid];
            var mpEditor = new MPEditor({
                id: _uuid,
                title: flowTitleList[idx],
                content: content ? content : '<p></p>',
                onSelectionChangeEvent: function(ueEditor) {
                    CurrUEditor = ueEditor;
                }
            });
            var element = mpEditor.element().appendTo(editorContainer);
            element.addClass('mp-content-container');
            mpEditor.init();
            MPEditorList.push(mpEditor);
        })();

        // tips
        (function() {
            var content = TipsMPEditorValueCache[_uuid];
            var tips = content ? content.tips : '';
            var mpEditor = new MPEditor({
                id: _uuid + '-tips',
                title: '- Tips',
                content: tips ? tips : '<p></p>',
                onSelectionChangeEvent: function(ueEditor) {
                    CurrUEditor = ueEditor;
                }
            });
            var element = mpEditor.element().appendTo(editorContainer);
            element.addClass('mp-tips-container');
            mpEditor.init();
            TipsMPEditorList.push(mpEditor);

            element.before(
                $('<div class="row mp-tips-plus"/>').append(
                        $('<div class="col-xs-12"/>').append(
                                $('<a href="javascript:;" title="编辑Tips"/>')
                                    .css({
                                        'line-height': '34px',
                                        'font-weight': 'bold'
                                    })
                                    .html('+ Tips')
                                    .click(function(e) {
                                        $(this).closest('.mp-tips-plus').next().show();
                                        $(this).closest('.mp-tips-plus').hide();
                                    })
                            )
                    )
            );
            $('.mp-editor-title label:first', element).click(function() {
                $(this).closest('.mp-tips-container').prev().show();
                $(this).closest('.mp-tips-container').hide();
            }).css({
                'cursor': 'pointer',
            });

            var tipsColorId = uuid();
            $('.mp-editor-title', element).append(
                $('<input type="hidden" name="tipsColor" />')
                    .attr('id', tipsColorId)
            );
            var colorList = ['#a8e6cf', '#bad7df', '#fdffab', '#ffd3b6', '#ffaaa5'];
            colorList.forEach(function(colorValue) {
                $('.mp-editor-title', element)
                    .append(
                        $('<label/>')
                            .css({
                                padding: '5px 0 5px 15px'
                            })
                            .append(
                                $('<input type="radio">')
                                    .attr('name', _uuid + '-tips-color')
                                    .attr('value', colorValue)
                                    .data('tipsColorId', tipsColorId)
                                    .css({
                                        position: 'relative',
                                        top: '2px'
                                    })
                                    .change(function() {
                                        if (this.checked) {
                                            var tipsColorId = $(this).data('tipsColorId');
                                            $('#' + tipsColorId).val(this.value);
                                        }
                                    })
                            )
                            .append(
                                $('<span>&nbsp;</span>')
                                    .css({
                                        'background-color': colorValue,
                                        padding: '5px 30px',
                                        'margin-left': '5px',
                                        cursor: 'pointer'
                                    })
                            )
                    );

            });

            if (content && content.tipsColor) {
                $('.mp-editor-title input[name="tipsColor"]', element).val(content.tipsColor);
                $('.mp-editor-title input[type="radio"][value="' + content.tipsColor + '"]', element).attr('checked', 'checked');
            }

        })();
    });

    $('.mp-tips-container', panel).hide();

    MPEditorValueCache = {};

    // $('.mp-insert-image', panel).unbind().click(function() {
    //     MPDialog.selectImageMaterial({
    //         cache: 'apply',
    //         siteId: App.getSiteId(),
    //         lang: App.getLang(),
    //         confirmCallback: function(list) {
    //             console.log('selected:', list);
    //             if (!CurrUEditor) {
    //                 return;
    //             }
    //             list.forEach(function(data) {
    //                 CurrUEditor
    //                     .execCommand( 'inserthtml',
    //                         '<p><img src="{0}"></p>'.format(data.url)
    //                     );
    //             });
    //         }
    //     });
    // });
}

// 备注
var RemarkMPEditorValueCache = null;
var RemarkMPEditor = null;
function initPostRemark(data) {

    var panel = $('.mp-panel-article-edit .mp-post-remark');
    var editorContainer = $('.mp-editor', panel);

    var mpEditor = new MPEditor({
        id: 'mp-post-remark-editor-container',
        content: (function() {
            return data ? data.remark : '<p></p>';
        })(),
        onSelectionChangeEvent: function(ueEditor) {
            CurrUEditor = ueEditor;
        }
    });
    mpEditor.element().appendTo(editorContainer);
    var ueEditor = mpEditor.init();
    RemarkMPEditor = mpEditor;

    // $('.mp-insert-image', panel).unbind().click(function() {
    //     MPDialog.selectImageMaterial({
    //         cache: 'apply',
    //         siteId: App.getSiteId(),
    //         lang: App.getLang(),
    //         confirmCallback: function(list) {
    //             console.log('selected:', list);
    //             list.forEach(function(data) {
    //                 CurrUEditor
    //                     .execCommand( 'inserthtml',
    //                         '<p><img src="{0}"></p>'.format(data.url)
    //                     );
    //             });
    //         }
    //     });
    // });

}

// 图片
function initPostImage(articleImage) {

    var panel = $('.mp-panel-article-edit .mp-post-image');
    var imageListTable = $('.mp-image-list', panel);
    var append = function(data) {
        var html = '';
        // html += '<div class="mp-col mp-col-6">';
        // html += '    <div style="background-color: black; margin-bottom: 15px;">';
        // html += '        <video class="post-video" controls="controls" preload="auto" width="100%" style="max-height: 480px;"></video>';
        // html += '    </div>';
        // html += '    <input type="hidden" name="id" value="" />';
        // html += '    <input type="hidden" name="articleVideo" value="" />';
        // html += '    <button type="button" class="btn btn-danger btn-xs mp-remove">删除</button>';
        // html += '    <div class="mp-col">';
        // html += '        图片名：' + data.videoName + '<br />';
        // html += '        文件名：' + data.videoFile;
        // html += '    </div>';
        // html += '</div>';
        html += '<div class="mp-box-block">';
        html += '	<div class="mp-box-top-toolbar">';
        html += '		<img class="mp-remove" src="theme/images/icon-remove.png">';
        html += '	</div>';
        html += '	<div class="mp-image-box">';
        html += '		<img class="img-rounded mp-image" src="theme/images/preview.png" data-holder-rendered="true" alt="" onerror="this.src=&quot;theme/images/preview.png&quot;">';
        html += '	</div>';
        html += '	<div class="mp-name">';
        html += '	    图片名：' + data.imageName + '<br>';
        html += '		文件名：' + data.imageFile;
        html += '	</div>';
        html += '   <input type="hidden" name="id" value="" />';
        html += '   <input type="hidden" name="articleImage" value="" />';
        html += '</div>';
        html = $(html).appendTo(imageListTable);
        $('.mp-image', html).attr('src', data.url);
        $('.mp-remove', html).click(function(e) {
            MPDialog.confirm({
                message: '确认删除？',
                confirmCallback: function() {
                    $(e.target).closest('.mp-box-block').remove();
                }
            });
        });
        $('input[name="id"]', html).val(data.id);
        $('input[name="articleImage"]', html).val(data.imageId);
    };

    articleImage && articleImage.forEach(function(data) {
        // var url = '/resource/mold/zhCN/video/{0}/download'.format(data.videoUrl);
        var url = '/support/res/{0}/{1}/material/pic/{2}'.format(App.getSiteId(), App.getLang(), data.imageUrl);
        append({
            id: data.id,
            imageId: data.imageId,
            imageName: data.imageFileName,
            imageFile: data.imageName,
            url: url
        });
    });

    $('.mp-post-image .mp-image-insert').unbind().click(function() {
        MPDialog.selectImageMaterial({
            cache: 'apply',
            siteId: App.getSiteId(),
            lang: App.getLang(),
            confirmCallback: function(list) {
                console.log('selected:', list);
                if (list.length == 0) {
                    return;
                }
                list.forEach(function(data) {
                    append({
                        id: 0,
                        imageId: data.uid,
                        imageName: data.file,
                        imageFile: data.name,
                        url: data.url
                    });
                });
            }
        });
    });
}

// 视频
function initPostVideo(articleVideo) {

    var panel = $('.mp-panel-article-edit .mp-post-video');
    var videoListTable = $('.mp-video-list', panel);
    var append = function(data) {
        var html = '';
        // html += '<div class="col-md-6">';
        // html += '    <div style="background-color: black; margin-bottom: 15px;">';
        // html += '        <video class="post-video" controls="controls" preload="auto" width="100%" style="max-height: 480px;"></video>';
        // html += '    </div>';
        // html += '    <input type="hidden" name="id" value="" />';
        // html += '    <input type="hidden" name="articleVideo" value="" />';
        // html += '    <button type="button" class="btn btn-danger btn-xs mp-remove">删除</button>';
        // html += '    <div class="mp-col">';
        // html += '        视频名：' + data.videoName + '<br />';
        // html += '        文件名：' + data.videoFile;
        // html += '    </div>';
        // html += '</div>';
        html += '<div class="mp-box-block">';
        html += '	<div class="mp-box-top-toolbar">';
        html += '		<img class="mp-remove" src="theme/images/icon-remove.png">';
        html += '	</div>';
        html += '	<div class="mp-video-box">';
        html += '		<img class="img-rounded mp-image" src="theme/images/preview-video.png" data-holder-rendered="true" alt="" onerror="this.src=&quot;theme/images/preview-video.png&quot;">';
        html += '	</div>';
        html += '	<div class="mp-name">';
        html += '		视频名：' + data.videoName + '<br>';
        html += '		文件名：' + data.videoFile;
        html += '	</div>';
        html += '   <input type="hidden" name="id" value="" />';
        html += '   <input type="hidden" name="articleVideo" value="" />';
        html += '</div>';
        html = $(html).appendTo(videoListTable);
        // $('.post-video', html)
        //     .append('<source src="{0}" type="video/mp4"/>'.format(data.playurl));
        $('.mp-remove', html).click(function(e) {
            MPDialog.confirm({
                message: '确认删除？',
                confirmCallback: function() {
                    $(e.target).closest('.mp-box-block').remove();
                }
            });
        });
        $('input[name="id"]', html).val(data.id);
        $('input[name="articleVideo"]', html).val(data.videoId);

        // 缩略图
        VideoScreenshotQueue = [];
        new VideoScreenshot({
            url: data.playurl,
            type: 'video/mp4',
            image: $('.mp-image', html)[0],
            callback: function(base64image) {

            }
        });
        runVideoScreenshotQueue();
    };

    articleVideo && articleVideo.forEach(function(data) {
        // var url = '/resource/mold/zhCN/video/{0}/download'.format(data.videoUrl);
        var url = '/support/res/{0}/{1}/material/mov/{2}'.format(App.getSiteId(), App.getLang(), data.videoUrl);
        append({
            id: data.id,
            videoId: data.videoId,
            videoName: data.videoFileName,
            videoFile: data.videoName,
            playurl: url
        });
    });

    $('.mp-post-video .mp-video-insert').unbind().click(function() {
        MPDialog.selectVideoMaterial({
            cache: 'apply',
            siteId: App.getSiteId(),
            lang: App.getLang(),
            confirmCallback: function(list) {
                console.log('selected:', list);
                if (list.length == 0) {
                    return;
                }
                list.forEach(function(data) {
                    append({
                        id: 0,
                        videoId: data.uid,
                        videoName: data.file,
                        videoFile: data.name,
                        playurl: data.playurl
                    });
                });
            }
        });
    });
}

// 相关文章
function initPostRelatedPost(relatedArticle) {

    var panel = $('.mp-panel-article-edit .mp-post-related-post');
    var tbody = $('table tbody', panel).empty();

    var isRepeat = function(id) {
        // 检查文章是否重复
        var result = false;
        $('tr', tbody).each(function(i, tr) {
            var m = $(tr).data('value');
            if (m.relatedArticle == id) {
                result = true;
                return false;
            }
        });
        return result;
    };

    var append = function(m) {
        var row = $('<tr/>').appendTo(tbody);
        row.data('value', m);
        $('<td class="mp-move-sort"/>').html('<i class="icon iconfont icon-move"></i>').appendTo(row);
        $('<td/>').html(m.title).appendTo(row);
        $('<td/>').html((function() {
            var div = $('<div/>');
            $('<input type="hidden" name="id" />').val(m.id).appendTo(div);
            $('<input type="hidden" name="relatedArticle" />').val(m.relatedArticle).appendTo(div);
            $('<button type="button" class="btn btn-danger btn-xs">删除</button>')
                .click(function(e) {
                    MPDialog.confirm({
                        message: '确认删除？',
                        confirmCallback: function() {
                            $(e.target).closest('tr').remove();
                        }
                    });
                })
                .appendTo(div);
            return div;
        })()).appendTo(row);
    };

    relatedArticle && relatedArticle
        .sort(function(a, b) {
            return a.index - b.index;
        })
        .forEach(function(m) {
            append({
                id: m.id,
                relatedArticle: m.relateArticleId,
                title: m.relateArticleTitle
            });
        });

    $('.mp-append', panel).unbind().click(function() {
        MPDialog.selectArticle({
            siteId: App.getSiteId(),
            lang: App.getLang(),
            confirmCallback: function(list) {
                console.log('selected:', list);
                if (list.length == 0) {
                    return;
                }
                var repeat = [];
                list
                    .filter(function(data) {
                        if (isRepeat(data.id)) {
                            repeat.push('　　' + data.title);
                            return false;
                        }
                        return true;
                    })
                    .forEach(function(data) {
                        append({
                            id: 0,
                            relatedArticle: data.id,
                            title: data.title
                        });
                    });
                if (repeat.length) {
                    MPDialog.alert({
                        message: '已过滤重复文章<br />' + repeat.join('<br />')
                    });
                }
            }
        });
    });

    // 拖动排序
    $(".mp-post-related-post table tbody").sortable({
        helper: function(e, tr) {
            var $originals = tr.children();
            var $helper = tr.clone();
            $helper.children().each(function(index) {
                $(this).width($originals.eq(index).width())
            });
            return $helper;
        },
        stop: function(e, ui) {
        }
    }).disableSelection();

}

// 相关视频
function initPostRelatedVideo(relatedVideo) {

    var panel = $('.mp-panel-article-edit .mp-post-related-video');
    var videoListTable = $('.mp-video-list', panel);
    var append = function(data) {
        var html = '';
        // html += '<div class="mp-row">';
        // html += '    <div class="mp-col">';
        // html += '        <div style="background-color: black; margin-bottom: 15px;">';
        // html += '            <video class="post-video" controls="controls" preload="auto" width="100%" style="max-height: 480px;"></video>';
        // html += '        </div>';
        // html += '    </div>';
        // html += '    <div class="mp-col vertical-middle text-right mp-col-10">';
        // html += '        <input type="hidden" name="id" value="" />';
        // html += '        <input type="hidden" name="relatedVideo" value="" />';
        // html += '        <button type="button" class="btn btn-danger btn-xs mp-remove">删除</button>';
        // html += '    </div>';
        // html += '</div>';
        // html += '<div class="mp-row">';
        // html += '    <div class="mp-col">';
        // html += '        视频名：' + data.videoName + '<br />';
        // html += '        文件名：' + data.videoFile;
        // html += '    </div>';
        // html += '</div>';
        html += '<div class="mp-box-block">';
        html += '	<div class="mp-box-top-toolbar">';
        html += '		<img class="mp-remove" src="theme/images/icon-remove.png">';
        html += '	</div>';
        html += '	<div class="mp-video-box">';
        html += '		<img class="img-rounded mp-image" src="theme/images/preview-video.png" data-holder-rendered="true" alt="" onerror="this.src=&quot;theme/images/preview-video.png&quot;">';
        html += '	</div>';
        html += '	<div class="mp-name">';
        html += '		视频名：' + data.videoName + '<br>';
        html += '		文件名：' + data.videoFile;
        html += '	</div>';
        html += '   <input type="hidden" name="id" value="" />';
        html += '   <input type="hidden" name="relatedVideo" value="" />';
        html += '</div>';
        html = $(html).appendTo(videoListTable);
        // $('.post-video', html)
        //     .append('<source src="{0}" type="video/mp4"/>'.format(data.playurl));
        $('.mp-remove', html).click(function(e) {
            MPDialog.confirm({
                message: '确认删除？',
                confirmCallback: function() {
                    $(e.target).closest('.mp-box-block').remove();
                }
            });
        });
        $('input[name="id"]', html).val(data.id);
        $('input[name="relatedVideo"]', html).val(data.videoId);

        // 缩略图
        VideoScreenshotQueue = [];
        new VideoScreenshot({
            url: data.playurl,
            type: 'video/mp4',
            image: $('.mp-image', html)[0],
            callback: function(base64image) {

            }
        });
        runVideoScreenshotQueue();
    };

    relatedVideo && relatedVideo.forEach(function(data) {
        // var url = '/resource/mold/zhCN/video/{0}/download'.format(data.videoName);
        var url = '/support/res/{0}/{1}/material/mov/{2}'.format(App.getSiteId(), App.getLang(), data.videoName);
        append({
            id: data.id,
            videoId: data.relateVideoId,
            videoName: data.videoFileName,
            videoFile: data.videoName,
            playurl: url
        });
    });

    $('.mp-post-related-video .mp-video-insert').unbind().click(function() {
        MPDialog.selectVideoMaterial({
            cache: 'apply',
            siteId: App.getSiteId(),
            lang: App.getLang(),
            confirmCallback: function(list) {
                console.log('selected:', list);
                if (list.length == 0) {
                    return;
                }
                list.forEach(function(data) {
                    append({
                        id: 0,
                        videoId: data.uid,
                        videoName: data.file,
                        videoFile: data.name,
                        playurl: data.playurl
                    });
                });
            }
        });
    });
}

// 标签
function initPostTag(data) {

    var panel = $('.mp-panel-article-edit .mp-post-tag');
    var content = $('.mp-tag-category', panel).empty();

    var build = function(response) {
        var list = response.data ? response.data.tags : [];
        var tagcatMap = {};
        list.forEach(function(tag) {
            var tc = tagcatMap[tag.catalog.id];
            if (!tc) {
                tc = tagcatMap[tag.catalog.id] = [];
            }
            tc.push(tag);
        });

        for (var catalogId in tagcatMap) {
            var tags = tagcatMap[catalogId];
            var catalog = tags[0].catalog;
            var html = '';
            html += '<div class="form-group">';
            html += '    <label class="col-sm-2 control-label">{0}</label>'.format(catalog.name);
            html += '    <div class="col-sm-10">';
            html += '        <select multiple class="form-control mp-select2-multiple" name="{0}">'.format(catalogId);
            html += '        </select>';
            html += '    </div>';
            html += '</div>';
            html = $(html).appendTo(content);
            var select = $('select', html);
            tags.forEach(function(tag) {
                select.append(
                    $('<option/>')
                        .attr('value', tag.id)
                        .text(tag.name)
                );
            });
        }

        // 选中
        if (data && data.tags) {
            $('select', panel).each(function(i, select) {
                data.tags.forEach(function(m, idx) {
                    $('option[value="{0}"]'.format(m.tagId), select)
                        .attr('selected', 'selected');
                });
            });
        }

        App.initSelect2Multiple(content);
    };

    var siteId = App.getSiteId();
    var condition = {};
    condition.catalogId = null;
    condition.name = null;
    condition.lang = App.getLang();
    condition.siteId = siteId;
    condition.start = 0;
    condition.size = 99999;
    Apis.getTags(condition, function(response) {
        build(response);
    });

}

/** *************************** 文章编辑 end */

// 获取文章内容
function formValueForArticle() {

    var data = {};

    var panel = $('.mp-panel-article-edit');

    (function() {
        var form = $('form.mp-post-info', panel);
        var values = formValue(form);
        values.id && (data.id = values.id);
    })();

    // 文章属性
    (function() {
        var form = $('form.mp-post-attribute', panel);
        var values = formValue(form);
        data.articleNo = values.articleNo;
        data.fileName = values.fileName;
        data.title = values.title;
    })();

    // 摘要
    data.summary = (function() {
        var form = $('form.mp-post-summary', panel);
        var values = formValue(form);
        return values.content ? values.content : '';
    })();

    // 流程简述2操作范例
    data.flow2OpSample = (function() {
        // TODO
        var form = $('form.mp-post-process-step', panel);
        var values = formValue(form, false, true);
        var flow2OpSample = [];
        if (values.flowId) {
            values.flowId.forEach(function(flowId, index) {
                var flow = values.flow[index];
                var opSampleId = values.opSampleId[index];
                flow2OpSample.push({flowId: flowId, flow: flow, opSampleId: opSampleId, opSamples: ''});
            });
        }
        return flow2OpSample;
    })();
    // 操作范例 & Tips
    (function() {
        var form = $('form.mp-post-step-standard', panel);
        var values = formValue(form, false, true);
        // console.log('操作范例 & Tips', values);
        // var content = values.content ? values.content : [];
        // var contentIndex = 0;
        // content.forEach(function(value, index) {
        //     if (index % 2 == 0) {
        //         // opSamples
        //         data.flow2OpSample[contentIndex].opSamples = value;
        //     } else {
        //         // Tips
        //         data.flow2OpSample[contentIndex].tips = value;
        //         data.flow2OpSample[contentIndex].tipsColor = values.tipsColor[contentIndex];
        //         contentIndex ++;
        //     }
        // });
        MPEditorList.forEach(function(mpEditor, index) {
            data.flow2OpSample[index].opSamples = mpEditor.getCache().content;
            data.flow2OpSample[index].tips = TipsMPEditorList[index].getCache().content;
            data.flow2OpSample[index].tipsColor = values.tipsColor[index];
        });
    })();

    // 图片
    data.articleImage = (function() {
        var form = $('form.mp-post-image', panel);
        var values = formValue(form, false, true);
        var articleImage = [];
        (values.articleImage ? values.articleImage : []).forEach(function(imageId, index) {
            var id = values.id[index];
            articleImage.push({id: id, imageId: imageId, index: index});
        });
        return articleImage;
    })();

    // 视频
    data.articleVideo = (function() {
        var form = $('form.mp-post-video', panel);
        var values = formValue(form, false, true);
        var articleVideo = [];
        (values.articleVideo ? values.articleVideo : []).forEach(function(videoId, index) {
            var id = values.id[index];
            articleVideo.push({id: id, videoId: videoId, index: index});
        });
        return articleVideo;
    })();

    // 备注
    data.remark = (function() {
        var form = $('form.mp-post-remark', panel);
        var values = formValue(form);
        return values.content ? values.content : '';
    })();

    // 相关文章
    data.relatedArticle = (function() {
        var form = $('form.mp-post-related-post', panel);
        var values = formValue(form, false, true);
        var relatedArticle = [];
        (values.relatedArticle ? values.relatedArticle : []).forEach(function(articleId, index) {
            var id = values.id[index];
            relatedArticle.push({id: id, articleId: articleId, index: index});
        });
        return relatedArticle;
    })();

    // 相关视频
    data.relatedVideo = (function() {
        var form = $('form.mp-post-related-video', panel);
        var values = formValue(form, false, true);
        var relatedVideo = [];
        (values.relatedVideo ? values.relatedVideo : []).forEach(function(videoId, index) {
            var id = values.id[index];
            relatedVideo.push({id: id, videoId: videoId, index: index});
        });
        return relatedVideo;
    })();

    // 标签
    data.tags = (function() {
        var form = $('form.mp-post-tag', panel);
        var values = formValue(form);
        var tags = [];
        for (var tagcatId in values) {
            tags.push({id: 0, tagcat: tagcatId, tags: values[tagcatId]});
        }
        return tags;
    })();

    return data;
}

// 校验文章必填项
function vaildateForArticle(data) {

    var returnValue = {
        result: true,
        message: ''
    };

    var messages = [];

    if (!data.articleNo) {
        returnValue.result = false;
        messages.push('自定义编号');
    }

    // if (!data.fileName) {
    //     returnValue.result = false;
    //     messages.push('文件名');
    // }

    if (!data.title) {
        returnValue.result = false;
        messages.push('标题');
    }

    if (!returnValue.result) {
        returnValue.message = messages.join('、').concat('是必填项');
    }

    return returnValue;
}

/** *************************** 分类 & 目录 */

// 显示分类列表
var FolderTypeList = [/*1, 7*/];
var FolderTypeMap = {
    // 1: '产品',
    // 7: '新闻',
    // 3: '技术领域',
    // 4: '案例',
};
var FolderCacheMap = {
    // 1: [],
    // 7: [],
};
function foldersViewList(action) {

    var panelElement = $('.mp-panel-category');
    var listContianer = $('table tbody', panelElement).empty();

    MPDialog.openWaiting();
    var buildList = function(list) {
        setTimeout(function() {
            MPDialog.closeWaiting();
        }, 1000);

        var ItemList = list
            .filter(function(m) {
                return m.type == 'Item';
            })
            .sort(function(a, b) {
                return a.sort - b.sort;
            });

        var CategoryList = list
            .filter(function(m) {
                return m.type == 'Category';
            })
            .sort(function(a, b) {
                return a.sort - b.sort;
            });

        list.forEach(function(m) {
            var row = $('<tr/>').appendTo(listContianer);
            row.data('value', m);
            $('<td/>').html((function () {
                return FolderTypeMap[m.itemId];
            })()).appendTo(row);
            $('<td/>').html(m.name).appendTo(row);
            $('<td/>')
                .append(
                    $('<button type="button" class="btn btn-default btn-xs">上移</button>')
                        .click(function(e) {

                            var currValue = $(this).closest('tr').data('value');
                            var prevValue = $(this).closest('tr').prev().data('value');
                            console.log('currValue', currValue);
                            console.log('prevValue', prevValue);
                            if (!prevValue || currValue.itemId != prevValue.itemId) {
                                return;
                            }

                            var parameter = {
                                forms: []
                            };

                            if (currValue.type === 'Item') {
                                ItemList
                                    .forEach(function (m, i) {
                                        m.sort = i;
                                    });
                                ItemList
                                    .forEach(function(m, i) {
                                        if (m.id == currValue.id) {
                                            currValue = m;
                                        } else if (m.id == prevValue.id) {
                                            prevValue = m;
                                        }
                                    });
                                var sort = currValue.sort;
                                currValue.sort = prevValue.sort;
                                prevValue.sort = sort;
                                ItemList
                                    .sort(function(a, b) {
                                        return a.sort - b.sort;
                                    })
                                    .forEach(function(m) {
                                        parameter.forms.push({
                                            siteId: App.getSiteId(),
                                            lang: App.getLang(),
                                            folderType: 0,
                                            folderId: m.id,
                                            sort: m.sort
                                        });
                                    });
                            }
                            else if (currValue.type === 'Category') {
                                CategoryList
                                    .forEach(function (m, i) {
                                        m.sort = i;
                                    });
                                CategoryList
                                    .forEach(function(m, i) {
                                        if (m.id == currValue.id) {
                                            currValue = m;
                                        } else if (m.id == prevValue.id) {
                                            prevValue = m;
                                        }
                                    });
                                var sort = currValue.sort;
                                currValue.sort = prevValue.sort;
                                prevValue.sort = sort;
                                CategoryList
                                    .sort(function(a, b) {
                                        return a.sort - b.sort;
                                    })
                                    .forEach(function(m) {
                                        parameter.forms.push({
                                            siteId: App.getSiteId(),
                                            lang: App.getLang(),
                                            folderType: 1,
                                            folderId: m.id,
                                            sort: m.sort
                                        });
                                    });
                            }
                            Apis.moveFolderSort(parameter, function(response) {
                                foldersViewList();
                            });
                        })
                )
                .append(
                    $('<button type="button" class="btn btn-default btn-xs">下移</button>')
                        .click(function(e) {

                            var currValue = $(this).closest('tr').data('value');
                            var nextValue = $(this).closest('tr').next().data('value');
                            console.log('currValue', currValue);
                            console.log('nextValue', nextValue);
                            if (!nextValue || currValue.type != nextValue.type) {
                                return;
                            }

                            var parameter = {
                                forms: []
                            };

                            if (currValue.type === 'Item') {
                                ItemList
                                    .forEach(function (m, i) {
                                        m.sort = i;
                                    });
                                ItemList
                                    .forEach(function(m, i) {
                                        if (m.id == currValue.id) {
                                            currValue = m;
                                        } else if (m.id == nextValue.id) {
                                            nextValue = m;
                                        }
                                    });
                                var sort = currValue.sort;
                                currValue.sort = nextValue.sort;
                                nextValue.sort = sort;
                                ItemList
                                    .sort(function(a, b) {
                                        return a.sort - b.sort;
                                    })
                                    .forEach(function(m) {
                                        parameter.forms.push({
                                            siteId: App.getSiteId(),
                                            lang: App.getLang(),
                                            folderType: 0,
                                            folderId: m.id,
                                            sort: m.sort
                                        });
                                    });
                            }
                            else if (currValue.type === 'Category') {
                                CategoryList
                                    .forEach(function (m, i) {
                                        m.sort = i;
                                    });
                                CategoryList
                                    .forEach(function(m, i) {
                                        if (m.id == currValue.id) {
                                            currValue = m;
                                        } else if (m.id == nextValue.id) {
                                            nextValue = m;
                                        }
                                    });
                                var sort = currValue.sort;
                                currValue.sort = nextValue.sort;
                                nextValue.sort = sort;
                                CategoryList
                                    .sort(function(a, b) {
                                        return a.sort - b.sort;
                                    })
                                    .forEach(function(m) {
                                        parameter.forms.push({
                                            siteId: App.getSiteId(),
                                            lang: App.getLang(),
                                            folderType: 1,
                                            folderId: m.id,
                                            sort: m.sort
                                        });
                                    });
                            }
                            Apis.moveFolderSort(parameter, function(response) {
                                foldersViewList();
                            });
                        })
                )
                .appendTo(row);
            $('<td/>')
                .append(
                    $('<button type="button" class="btn btn-warning btn-xs">修改</button>')
                        .click(function(e) {
                            var m = $(this).closest('tr').data('value');
                            MPDialog.categoryAppend({
                                data: {
                                    id: m.id,
                                    itemId: m.itemId,
                                    name: m.name,
                                    sort: m.sort
                                },
                                confirmCallback: function() {
                                    foldersViewList();
                                }
                            });
                        })
                )
                .append(
                    $('<button type="button" class="btn btn-danger btn-xs">删除</button>')
                        .click(function(e) {
                            var m = $(this).closest('tr').data('value');
                            MPDialog.confirm({
                                message: '确认删除?',
                                confirmCallback: function() {
                                    if (App.getLang() == 'zhCN') {
                                        var parameter = {
                                            siteId: App.getSiteId(),
                                            folderType: (function() {
                                                switch (m.type) {
                                                    case 'Item': return '0';
                                                    case 'Category': return '1';
                                                    case 'Hot': return '2';
                                                }
                                            })(),
                                            lang: App.getLang(),
                                            id: m.id
                                        };
                                        Apis.getFolderLangAll(parameter, function(response) {
                                            var list = response.data;
                                            var parameter = {
                                                id: [],
                                                type: (function() {
                                                    switch (m.type) {
                                                        case 'Item': return '0';
                                                        case 'Category': return '1';
                                                        case 'Hot': return '2';
                                                    }
                                                })()
                                            };
                                            list.forEach(function(m) {
                                                parameter.id.push(m.id);
                                            });
                                            Apis.delFolderLangAll(parameter, function() {
                                                foldersViewList();
                                            });
                                        });
                                        return;
                                    }
                                    Apis.deleteFolder({id: m.id, type: (function() {
                                            switch (m.type) {
                                                case 'Item': return 0;
                                                case 'Category': return 1;
                                                case 'Hot': return 2;
                                            }
                                        })()}, function() {
                                        foldersViewList();
                                    });
                                }
                            });
                        })
                )
                .appendTo(row);
        });
    };

    var init = new Chain();
    if (!action) {
        init.method(function(next, _) {

            FolderTypeList = [];
            FolderTypeMap = {};
            FolderCacheMap = {};

            var condition = {};
            condition.lang = App.getLang();
            condition.siteId = App.getSiteId();
            condition.folderType = 0;
            Apis.getFolders(condition, function(response) {
                var list = response.data.folders;
                var select = $('[name="itemId"]', panelElement).empty();
                select.append('<option value="">请选择</option>');
                list.forEach(function(folder) {
                    FolderTypeList.push(folder.id);
                    FolderTypeMap[folder.id] = folder.name;
                    FolderCacheMap[folder.id] = [];
                    $('<option/>')
                        .attr('value', folder.id)
                        .html(folder.name)
                        .appendTo(select);
                });
                $('div.mp-select2', panelElement).remove();
                $('select.mp-select2', panelElement)
                    .removeClass('select2-offscreen')
                    .removeAttr('tabindex');
                App.initSelect2(panelElement);
                $('.select2-drop:last').css('z-index', 99999);
                next();
            });
        });
    }
    init.method(function(next, _) {
        var condition = formValue($('form', panelElement));
        condition.folderType = 1;
        condition.lang = App.getLang();
        condition.siteId = App.getSiteId();
        condition.name = condition.name ? condition.name : null;
        Apis.getFolders(condition, function(response) {
            var list = response.data ? response.data.folders : [];
            if (!list || list.length == 0) {
                return;
            }
            FolderTypeList.forEach(function(folderTypeItemId) {
                FolderCacheMap[folderTypeItemId] = list
                    .filter(function(m) {
                        if (condition.itemId) {
                            return m.itemId == folderTypeItemId && m.itemId == condition.itemId;
                        }
                        return m.itemId == folderTypeItemId;
                    })
                    .sort(function(a, b) {
                        return a.sort - b.sort;
                    });
                buildList(FolderCacheMap[folderTypeItemId]);
            });
            next();
        });
    });
    init.start();

}

// 显示目录树结构
var CurrTreeView = null;
var CurrTreeNodeInfo = null;
// Item(0), Category(1), Hot(2);
var rootMap = {};
var categoryMap = {};

// 显示索引
function foldersTreeView() {

    MPDialog.openWaiting();

    resetNode(function() {

    });

    var panelElement = $('.mp-panel-folder');
    var treeviewContianer = $('.mp-treeview', panelElement);

    // var build = function(folders, articles) {
    //     // folders.forEach(function(folder, idx) {
    //     //     var node = {
    //     //         icon: "icon iconfont icon-icon-test",
    //     //         text: folder.name,
    //     //         tags: [folder.id + '', folder.type, 'Folder'],
    //     //         nodes: []
    //     //     };
    //     //     rootMap[folder.type].nodes.push(node);
    //     //     // Item(0), Category(1), Hot(2);
    //     //     switch (folder.type) {
    //     //         case 'Item':
    //     //             itemCategoryMap[folder.id] = node;
    //     //             break;
    //     //         case 'Category':
    //     //             cateCategoryMap[folder.id] = node;
    //     //             break;
    //     //         // case 'Hot':
    //     //         //     hotCategoryMap[folder.id] = node;
    //     //         //     break;
    //     //     }
    //     // });
    //     //
    //     // articles.forEach(function(folder) {
    //     //     var folderType = folder.type;
    //     //     folder.articles
    //     //         .sort(function(a, b) {
    //     //             return a.sort - b.sort;
    //     //         })
    //     //         .forEach(function(article) {
    //     //             var folderId = article.folderId;
    //     //             var fileNode = {
    //     //                 icon: "icon iconfont icon-file",
    //     //                 text: article.articleNo + ' ' + article.articleTile,
    //     //                 tags: [article.articleId + '', folderType, 'Article'],
    //     //             };
    //     //             // Item(0), Category(1), Hot(2);
    //     //             switch (folderType) {
    //     //                 case 'Item':
    //     //                     var _folder = itemCategoryMap[folderId];
    //     //                     if (_folder) {
    //     //                         var _nodes = _folder.nodes;
    //     //                         if (_nodes)
    //     //                             _nodes.push(fileNode);
    //     //                     }
    //     //                     break;
    //     //                 case 'Category':
    //     //                     var _folder = cateCategoryMap[folderId];
    //     //                     if (_folder) {
    //     //                         var _nodes = _folder.nodes;
    //     //                         if (_nodes)
    //     //                             _nodes.push(fileNode);
    //     //                     }
    //     //                     break;
    //     //                 case 'Hot':
    //     //                     var _nodes = hotCategoryMap.nodes;
    //     //                     if (_nodes)
    //     //                         _nodes.push(fileNode);
    //     //                     break;
    //     //             }
    //     //         });
    //     // });
    //     //
    //     // treeview([
    //     //     rootMap.Item,
    //     //     rootMap.Category,
    //     //     rootMap.Hot
    //     // ]);
    //     treeview(FolderTypeList.map(function(itemId) {
    //         return rootMap['' + itemId];
    //     }));
    // };

    var folders = [];

    var task = new Chain();
    task.method(function(next, _) {

        FolderTypeList = [];
        FolderTypeMap = {};
        FolderCacheMap = {};

        var condition = {};
        condition.lang = App.getLang();
        condition.siteId = App.getSiteId();
        condition.folderType = 0;
        Apis.getFolders(condition, function(response) {
            var list = response.data.folders;
            list.forEach(function(folder) {
                FolderTypeList.push(folder.id);
                FolderTypeMap[folder.id] = folder.name;
                FolderCacheMap[folder.id] = [];
            });
            next();
        });
    });
    task.method(function(next, _) {
        var condition = {};
        condition.lang = App.getLang();
        condition.siteId = App.getSiteId();
        condition.folderType = 0;
        Apis.getFolders(condition, function(response) {
            folders = response.data.folders;
            folders.forEach(function(folder) {
                rootMap[folder.itemId] = {
                    icon: "icon iconfont icon-icon-test",
                    text: folder.name,
                    tags: ['0', 'Item', 'Root'],
                    nodes: [
                        // {
                        //     icon: "icon iconfont icon-icon-test",
                        //     text: '分类',
                        //     tags: ['0'],
                        //     nodes: [
                        //         {
                        //             icon: "icon iconfont icon-file",
                        //             text: 'A1-1 安装到NX',
                        //             tags: ['0']
                        //         }
                        //     ]
                        // }
                    ]
                };
            });

            next();
        });
    });
    task.method(function(next, _) {
        var condition = {};
        condition.lang = App.getLang();
        condition.siteId = App.getSiteId();
        condition.folderType = 1;
        Apis.getFolders(condition, function(response) {
            folders = response.data.folders;
            folders.forEach(function(folder) {
                var node = {
                    icon: "icon iconfont icon-icon-test",
                    text: folder.name,
                    tags: [folder.id + '', folder.type, 'Folder'],
                    nodes: [
                        // {
                        //     icon: "icon iconfont icon-icon-test",
                        //     text: '分类',
                        //     tags: ['0'],
                        //     nodes: [
                        //         {
                        //             icon: "icon iconfont icon-file",
                        //             text: 'A1-1 安装到NX',
                        //             tags: ['0']
                        //         }
                        //     ]
                        // }
                    ]
                };
                categoryMap[folder.id] = node;
                var item = rootMap[folder.itemId];
                if (item && item.nodes) {
                    item.nodes.push(node);
                }
            });

            next();
        });
    });
    task.method(function(next, _) {
        var condition = {};
        condition.lang = App.getLang();
        condition.siteId = App.getSiteId();
        condition.isDetail = false;
        Apis.getArticlesIndex(condition, function(response) {
            var index = response.data;
            index
                .sort(function(a, b) {
                    return a.sort - b.sort;
                })
                .forEach(function(folder) {
                    var folderType = folder.type;
                    var _folder = categoryMap[folder.folderId];
                    if (_folder) {
                        folder.articles.forEach(function(article) {
                            var fileNode = {
                                icon: "icon iconfont icon-file",
                                text: article.articleNo + ' ' + article.articleTile,
                                tags: [article.articleId + '', folderType, 'Article'],
                            };
                            _folder.nodes.push(fileNode);
                        });
                    }
                });

            next();
        });
    });
    task.method(function(next, _) {
        treeview(FolderTypeList.map(function(itemId) {
            return rootMap['' + itemId];
        }));
        setTimeout(function() {
            MPDialog.closeWaiting();
        }, 1000);
        next();
    });
    task.start();

    enableScrollListener();
    setScrollListener('mp-panel-folder-float', function(jWindow) {
        var spyBody = $('.mp-panel-folder');
        var position = spyBody.offset();
        var wTop = jWindow.scrollTop();
        if (wTop >= position.top) {
            // show
            var floatPanel = $('.mp-panel-folder-float');
            if (floatPanel.is(':hidden')) {
                floatPanel.show();
            }
        } else {
            // hide
            var floatPanel = $('.mp-panel-folder-float');
            if (!floatPanel.is(':hidden')) {
                floatPanel.hide();
            }
        }
    });

}

// 重置索引，清空索引UI
function resetNode(callback) {
    var panelElement = $('.mp-panel-folder');

    $('.mp-node-append', panelElement).unbind().attr('disabled', 'disabled');
    $('.mp-delete', panelElement).unbind().attr('disabled', 'disabled');
    $('.mp-move-up', panelElement).unbind().attr('disabled', 'disabled');
    $('.mp-move-down', panelElement).unbind().attr('disabled', 'disabled');

    CurrTreeView = null;
    CurrTreeNodeInfo = null;
    rootMap = {};

    callback();
}

// 显示
function treeview(treedata) {
    if (CurrTreeView) {
        var state = {
            expanded: {}
        };
        for (var i = 0; i < 20000; i++) {
            var node = $('#treeview5').treeview('getNode', i);
            if (node.nodeId > -1) {
                var nodeType = node.tags[2];
                if (['Root', 'Folder'].indexOf(nodeType) > -1) {
                    state.expanded[node.nodeId] = node.state.expanded;
                    state.expanded[node.text] = node.state.expanded;
                }
                continue;
            }
            break;
        }
        treedata.forEach(function(node) {
            if (!node) {
                console.log('node');
                return;
            }
            var nodeType = node.tags[2];
            if (['Root', 'Folder'].indexOf(nodeType) > -1) {
                var expanded = state.expanded[node.nodeId];
                if (expanded == undefined) {
                    expanded = state.expanded[node.text];
                }
                node.state = node.state ?　node.state : {expanded: false};
                node.state.expanded = expanded;
            }
            node.nodes.forEach(function(n) {
                var nodeType = n.tags[2];
                if (['Root', 'Folder'].indexOf(nodeType) > -1) {
                    var expanded = state.expanded[n.nodeId];
                    if (expanded == undefined) {
                        expanded = state.expanded[n.text];
                    }
                    n.state = n.state ?　n.state : {expanded: false};
                    n.state.expanded = expanded;
                }
            });
        });
    }

    CurrTreeView = $('#treeview5').treeview({
        // levels: 3,
        color: "#333",
        expandIcon: 'icon iconfont icon-right',
        collapseIcon: 'icon iconfont icon-bottom',
        emptyIcon: '',
        nodeIcon: '',
        data: treedata,
        onNodeSelected: function(event, data) {
            onNodeSelected(data);
        }
    });
}

// 选择事件处理
function onNodeSelected(data) {

    var panelElement = $('.mp-panel-folder');
    var floatPanelElement = $('.mp-panel-folder-float');
    var treeviewContianer = $('.mp-treeview', panelElement);

    var info = getNodeInfo(data.nodeId);
    CurrTreeNodeInfo = info;
    console.log(info);

    $('.mp-node-append', panelElement).unbind().attr('disabled', 'disabled');
    $('.mp-delete', panelElement).unbind().attr('disabled', 'disabled');
    $('.mp-move-up', panelElement).unbind().attr('disabled', 'disabled');
    $('.mp-move-down', panelElement).unbind().attr('disabled', 'disabled');

    $('.mp-node-append', floatPanelElement).unbind().attr('disabled', 'disabled')
        .click(function() {
            $('.mp-node-append', panelElement).click();
        });
    $('.mp-delete', floatPanelElement).unbind().attr('disabled', 'disabled')
        .click(function() {
            $('.mp-delete', panelElement).click();
        });
    $('.mp-move-up', floatPanelElement).unbind().attr('disabled', 'disabled')
        .click(function() {
            $('.mp-move-up', panelElement).click();
        });
    $('.mp-move-down', floatPanelElement).unbind().attr('disabled', 'disabled')
        .click(function() {
            $('.mp-move-down', panelElement).click();
        });

    if (info.isDirectory) {
        if (['Item', 'Category', 'Hot'].indexOf(info.type) > -1) {
            $('.mp-node-append', floatPanelElement).removeAttr('disabled');
            $('.mp-node-append', panelElement).removeAttr('disabled').click(function() {
                MPDialog.selectArticle({
                    siteId: App.getSiteId(),
                    lang: App.getLang(),
                    confirmCallback: function(list) {
                        console.log('selected:', list);
                        if (list.length == 0) {
                            return;
                        }
                        var checkExist = false;
                        var existArticleIds = CurrTreeNodeInfo.selectedNode.nodes
                            .map(function(data) {
                                return data.tags[0];
                            });
                        list = list.filter(function(data) {
                            var articleId = data.id + '';
                            if (existArticleIds.indexOf(articleId) > -1) {
                                checkExist = true;
                                return false;
                            }
                            return true;
                        });
                        if (checkExist) {
                            MPDialog.alert({
                                message: '有重复文章, 已过滤重复文章'
                            });
                            // return;
                        }
                        list.forEach(function(data) {

                            var nodeType = CurrTreeNodeInfo.selectedNode.tags[2];
                            var folderType = CurrTreeNodeInfo.selectedNode.tags[1];
                            var folderId = CurrTreeNodeInfo.selectedNode.tags[0];

                            var sort = CurrTreeNodeInfo.selectedNode.nodes.length;

                            var newNode = {
                                icon: "icon iconfont icon-file",
                                text: data.articleNo + ' ' + data.title,
                                tags: [data.id + '', folderType, 'Article'],
                            };

                            console.log(nodeType, folderType, folderId, sort, newNode, CurrTreeNodeInfo.selectedNode);

                            FolderTypeList.forEach(function(itemId) {
                                var folder = rootMap['' + itemId];
                                if (folder) {
                                    folder.nodes.forEach(function(node) {
                                        if (node.tags[0] == ('' + folderId)) {
                                            node.nodes.push(newNode);
                                        }
                                    });
                                }
                            });

                            var parameter = {
                                siteId: App.getSiteId(),
                                lang: App.getLang(),

                                folderId: folderId,
                                folderType: 1,
                                articles: [{articleId: data.id, sort: sort}] // {articleId: 0, sort: 0}
                            };
                            Apis.addArticleToFolder(parameter, function(response) {

                                // 刷新显示
                                treeview(FolderTypeList.map(function(itemId) {
                                    return rootMap['' + itemId];
                                }));

                            });

                            // // Item(0), Category(1), Hot(2);
                            // switch (folderType) {
                            //     case 'Item':
                            //         itemCategoryMap[folderId].nodes.push(newNode);
                            //         var parameter = {
                            //             siteId: App.getSiteId(),
                            //             lang: App.getLang(),
                            //
                            //             folderId: folderId,
                            //             folderType: 0,
                            //             articles: [{articleId: data.id, sort: sort}] // {articleId: 0, sort: 0}
                            //         };
                            //         Apis.addArticleToFolder(parameter, function(response) {
                            //
                            //         });
                            //         break;
                            //     case 'Category':
                            //         cateCategoryMap[folderId].nodes.push(newNode);
                            //         var parameter = {
                            //             siteId: App.getSiteId(),
                            //             lang: App.getLang(),
                            //
                            //             folderId: folderId,
                            //             folderType: 1,
                            //             articles: [{articleId: data.id, sort: sort}] // {articleId: 0, sort: 0}
                            //         };
                            //         Apis.addArticleToFolder(parameter, function(response) {
                            //
                            //         });
                            //         break;
                            //     case 'Hot':
                            //         hotCategoryMap.nodes.push(newNode);
                            //         var parameter = {
                            //             siteId: App.getSiteId(),
                            //             lang: App.getLang(),
                            //
                            //             folderId: 1,
                            //             folderType: 2,
                            //             articles: [{articleId: data.id, sort: sort}] // {articleId: 0, sort: 0}
                            //         };
                            //         Apis.addArticleToFolder(parameter, function(response) {
                            //
                            //         });
                            //         break;
                            // }
                            // 刷新显示
                            // treeview([
                            //     rootMap.Item,
                            //     rootMap.Category,
                            //     rootMap.Hot
                            // ]);

                            // if (list.length == 1) {
                            //     // 选中添加的节点
                            //     var folderNode = CurrTreeView.treeview('getNode', CurrTreeNodeInfo.selectedNode.nodeId);
                            //     var node = folderNode.nodes[folderNode.nodes.length - 1];
                            //     CurrTreeView.treeview('selectNode', node.nodeId);
                            // }
                        });
                    }
                });
            });
        }
    }
    if (info.isFile) {
        $('.mp-delete', floatPanelElement).removeAttr('disabled');
        $('.mp-delete', panelElement).removeAttr('disabled').click(function() {
            console.log('delete', CurrTreeNodeInfo);
            MPDialog.confirm({
                message: '确认删除?',
                confirmCallback: function() {
                    console.log('delete', 'confirm');
                    var folderType = CurrTreeNodeInfo.type;
                    var folderId = CurrTreeNodeInfo.parentNode.tags[0];
                    var articleId = CurrTreeNodeInfo.selectedNode.tags[0];

                    categoryMap[folderId].nodes = categoryMap[folderId].nodes.filter(function(article) {
                        if (CurrTreeNodeInfo.selectedNode.tags[0] != article.tags[0]) {
                            return true;
                        }
                        return false;
                    });
                    var parameter = {
                        siteId: App.getSiteId(),
                        lang: App.getLang(),

                        folderId: folderId,
                        folderType: 1,
                        articleIds: [articleId]
                    };
                    Apis.deleteArticleFromFolder(parameter, function(response) {

                        // 刷新显示
                        treeview(FolderTypeList.map(function(itemId) {
                            return rootMap['' + itemId];
                        }));

                    });

                    // // Item(0), Category(1), Hot(2);
                    // switch (folderType) {
                    //     case 'Item':
                    //         itemCategoryMap[folderId].nodes = itemCategoryMap[folderId].nodes.filter(function(article) {
                    //             if (articleId != article.tags[0]) {
                    //                 return true;
                    //             }
                    //             return false;
                    //         });
                    //         var parameter = {
                    //             siteId: App.getSiteId(),
                    //             lang: App.getLang(),
                    //
                    //             folderId: folderId,
                    //             folderType: 0,
                    //             articleIds: [articleId]
                    //         };
                    //         Apis.deleteArticleFromFolder(parameter, function(response) {
                    //
                    //         });
                    //         break;
                    //     case 'Category':
                    //         cateCategoryMap[folderId].nodes = cateCategoryMap[folderId].nodes.filter(function(article) {
                    //             if (CurrTreeNodeInfo.selectedNode.tags[0] != article.tags[0]) {
                    //                 return true;
                    //             }
                    //             return false;
                    //         });
                    //         var parameter = {
                    //             siteId: App.getSiteId(),
                    //             lang: App.getLang(),
                    //
                    //             folderId: folderId,
                    //             folderType: 1,
                    //             articleIds: [articleId]
                    //         };
                    //         Apis.deleteArticleFromFolder(parameter, function(response) {
                    //
                    //         });
                    //         break;
                    //     case 'Hot':
                    //         hotCategoryMap.nodes = hotCategoryMap.nodes.filter(function(article) {
                    //             if (CurrTreeNodeInfo.selectedNode.tags[0] != article.tags[0]) {
                    //                 return true;
                    //             }
                    //             return false;
                    //         });
                    //         var parameter = {
                    //             siteId: App.getSiteId(),
                    //             lang: App.getLang(),
                    //
                    //             folderId: 1,
                    //             folderType: 2,
                    //             articleIds: [articleId]
                    //         };
                    //         Apis.deleteArticleFromFolder(parameter, function(response) {
                    //
                    //         });
                    //         break;
                    // }
                    //
                    // // 刷新显示
                    // treeview([
                    //     rootMap.Item,
                    //     rootMap.Category,
                    //     rootMap.Hot
                    // ]);
                }
            });
        });
        if (info.prevNode != null) {
            $('.mp-move-up', floatPanelElement).removeAttr('disabled');
            $('.mp-move-up', panelElement).removeAttr('disabled').click(function() {
                console.log('moveUp', CurrTreeNodeInfo);
                var folderType = CurrTreeNodeInfo.type;
                var folderId = CurrTreeNodeInfo.parentNode.tags[0];
                var articleId = CurrTreeNodeInfo.selectedNode.tags[0];
                var articleId1 = -1;
                var articleId2 = -1;
                var index1 = -1;
                var index2 = -1;
                CurrTreeNodeInfo.parentNode.nodes.forEach(function(node, idx) {
                    var id = CurrTreeNodeInfo.selectedNode.tags[0];
                    if (node.tags[0] == id) {
                        index1 = idx;
                        articleId1 = node.tags[0];
                    } else if (node.tags[0] == CurrTreeNodeInfo.prevNode.tags[0]) {
                        index2 = idx;
                        articleId2 = node.tags[0];
                    }
                    node.state.selected = false;
                });
                var data1 = CurrTreeNodeInfo.parentNode.nodes[index1];
                var data2 = CurrTreeNodeInfo.parentNode.nodes[index2];
                CurrTreeNodeInfo.parentNode.nodes[index1] = data2;
                CurrTreeNodeInfo.parentNode.nodes[index2] = data1;
                // Item(0), Category(1), Hot(2);
                switch (folderType) {
                    // case 'Item':
                    //     itemCategoryMap[folderId].nodes = CurrTreeNodeInfo.parentNode.nodes;
                    //     var siteId = App.getSiteId();
                    //     var lang = App.getLang();
                    //     var parameter = {
                    //         forms: []
                    //     };
                    //     CurrTreeNodeInfo.parentNode.nodes.forEach(function(node, idx) {
                    //         var arctileId = node.tags[0];
                    //         var form = {
                    //             siteId: siteId,
                    //             lang: lang,
                    //             folderType: 0,
                    //             folderId: folderId,
                    //             arctileId: arctileId,
                    //             sort: idx,
                    //         };
                    //         parameter.forms.push(form);
                    //     });
                    //     Apis.moveArticleSort(parameter, function(response) {});
                    //     break;
                    case 'Category':
                        categoryMap[folderId].nodes = CurrTreeNodeInfo.parentNode.nodes;
                        var siteId = App.getSiteId();
                        var lang = App.getLang();
                        var parameter = {
                            forms: []
                        };
                        CurrTreeNodeInfo.parentNode.nodes.forEach(function(node, idx) {
                            var arctileId = node.tags[0];
                            var form = {
                                siteId: siteId,
                                lang: lang,
                                folderType: 1,
                                folderId: folderId,
                                arctileId: arctileId,
                                sort: idx,
                            };
                            parameter.forms.push(form);
                        });
                        Apis.moveArticleSort(parameter, function(response) {

                            // 刷新显示
                            treeview(FolderTypeList.map(function(itemId) {
                                return rootMap['' + itemId];
                            }));

                            // 选中添加的节点
                            var nodeId = CurrTreeNodeInfo.selectedNode.nodeId - 1;
                            var info = getNodeInfo(nodeId);
                            if (info.selectedNode.tags[2] == 'Article') {
                                CurrTreeView.treeview('selectNode', nodeId);
                                CurrTreeNodeInfo = info;
                            }
                            onNodeSelected(info.selectedNode);

                        });
                        break;
                }

                //
                // // 刷新显示
                // treeview([
                //     rootMap.Item,
                //     rootMap.Category,
                //     rootMap.Hot
                // ]);
                //
                // // 选中添加的节点
                // var nodeId = CurrTreeNodeInfo.selectedNode.nodeId - 1;
                // var info = getNodeInfo(nodeId);
                // if (info.selectedNode.tags[2] == 'Article') {
                //     CurrTreeView.treeview('selectNode', nodeId);
                //     CurrTreeNodeInfo = info;
                // }
                // onNodeSelected(info.selectedNode);

            });
        }
        if (info.nextNode != null) {
            $('.mp-move-down', floatPanelElement).removeAttr('disabled');
            $('.mp-move-down', panelElement).removeAttr('disabled').click(function() {
                console.log('moveDown', CurrTreeNodeInfo);
                var folderType = CurrTreeNodeInfo.type;
                var folderId = CurrTreeNodeInfo.parentNode.tags[0];
                var articleId = CurrTreeNodeInfo.selectedNode.tags[0];
                var articleId1 = -1;
                var articleId2 = -1;
                var index1 = -1;
                var index2 = -1;
                CurrTreeNodeInfo.parentNode.nodes.forEach(function(node, idx) {
                    if (node.tags[0] == CurrTreeNodeInfo.selectedNode.tags[0]) {
                        index1 = idx;
                        articleId1 = node.tags[0];
                    } else if (node.tags[0] == CurrTreeNodeInfo.nextNode.tags[0]) {
                        index2 = idx;
                        articleId2 = node.tags[0];
                    }
                    node.state.selected = false;
                });
                var data1 = CurrTreeNodeInfo.parentNode.nodes[index1];
                var data2 = CurrTreeNodeInfo.parentNode.nodes[index2];
                CurrTreeNodeInfo.parentNode.nodes[index1] = data2;
                CurrTreeNodeInfo.parentNode.nodes[index2] = data1;
                // Item(0), Category(1), Hot(2);
                switch (folderType) {
                    // case 'Item':
                    //     itemCategoryMap[folderId].nodes = CurrTreeNodeInfo.parentNode.nodes;
                    //     var siteId = App.getSiteId();
                    //     var lang = App.getLang();
                    //     var parameter = {
                    //         forms: []
                    //     };
                    //     CurrTreeNodeInfo.parentNode.nodes.forEach(function(node, idx) {
                    //         var arctileId = node.tags[0];
                    //         var form = {
                    //             siteId: siteId,
                    //             lang: lang,
                    //             folderType: 0,
                    //             folderId: folderId,
                    //             arctileId: arctileId,
                    //             sort: idx,
                    //         };
                    //         parameter.forms.push(form);
                    //     });
                    //     Apis.moveArticleSort(parameter, function(response) {});
                    //     break;
                    case 'Category':
                        categoryMap[folderId].nodes = CurrTreeNodeInfo.parentNode.nodes;
                        var siteId = App.getSiteId();
                        var lang = App.getLang();
                        var parameter = {
                            forms: []
                        };
                        CurrTreeNodeInfo.parentNode.nodes.forEach(function(node, idx) {
                            var arctileId = node.tags[0];
                            var form = {
                                siteId: siteId,
                                lang: lang,
                                folderType: 1,
                                folderId: folderId,
                                arctileId: arctileId,
                                sort: idx,
                            };
                            parameter.forms.push(form);
                        });
                        Apis.moveArticleSort(parameter, function(response) {

                            // 刷新显示
                            treeview(FolderTypeList.map(function(itemId) {
                                return rootMap['' + itemId];
                            }));

                            // 选中添加的节点
                            var nodeId = CurrTreeNodeInfo.selectedNode.nodeId + 1;
                            var info = getNodeInfo(nodeId);
                            if (info.selectedNode.tags[2] == 'Article') {
                                CurrTreeView.treeview('selectNode', nodeId);
                                CurrTreeNodeInfo = info;
                            }
                            onNodeSelected(info.selectedNode);

                        });
                        break;
                }

                // // 刷新显示
                // treeview([
                //     rootMap.Item,
                //     rootMap.Category,
                //     rootMap.Hot
                // ]);
                //
                // // 选中添加的节点
                // var nodeId = CurrTreeNodeInfo.selectedNode.nodeId + 1;
                // var info = getNodeInfo(nodeId);
                // if (info.selectedNode.tags[2] == 'Article') {
                //     CurrTreeView.treeview('selectNode', nodeId);
                //     CurrTreeNodeInfo = info;
                // }
                // onNodeSelected(info.selectedNode);
            });
        }
    }
}

function getNodeInfo(nodeId) {
    var data = CurrTreeView.treeview('getNode', nodeId);
    var parentNode = CurrTreeView.treeview('getParent', nodeId);
    var prevNode = CurrTreeView.treeview('getNode', nodeId - 1);
    var nextNode = CurrTreeView.treeview('getNode', nodeId + 1);
    var siblins = CurrTreeView.treeview('getSiblings', nodeId);

    parentNode = (function() {
        if (parentNode.context) {
            return null;
        }
        return parentNode;
    })();
    prevNode = (function() {
        if (prevNode.context) {
            return null;
        }
        if (prevNode.tags[1] != data.tags[1] || prevNode.tags[2] != data.tags[2]) {
            return null;
        }
        return prevNode;
    })();
    nextNode = (function() {
        if (nextNode.context) {
            return null;
        }
        if (nextNode.tags[1] != data.tags[1] || nextNode.tags[2] != data.tags[2]) {
            return null;
        }
        return nextNode;
    })();

    var info = {
        type: data.tags[1],
        isDirectory: (function() {
            if (data.tags[2] == 'Folder') {
                return true;
            }
            return data.tags[1] == 'Hot' && data.tags[2] != 'Article'
        })(),
        isFile: data.tags[2] == 'Article',
        selectedNode: data,
        prevNode: prevNode,
        nextNode: nextNode,
        parentNode: parentNode,
        siblins: siblins
    };

    return info;
}

/** *************************** 账号 */

function accountViewList() {

    var panelElement = $('.mp-panel-users');
    var listContianer = $('table tbody', panelElement).empty();

    MPDialog.openWaiting();
    var build = function(response) {
        setTimeout(function() {
            MPDialog.closeWaiting();
        }, 1000);

        var list = response.data ? response.data : [];

        if (!list || list.length == 0) {
            return;
        }

        list.forEach(function(m) {
            var row = $('<tr/>').appendTo(listContianer);
            row.data('value', m);
            $('<td/>').html(m.userName).appendTo(row);
            $('<td/>').html(m.loginName).appendTo(row);
            $('<td/>').html(m.siteId).appendTo(row);
            $('<td/>').html((function() {
                if (m.role == 1) {
                    return '超级管理员';
                }
                if (m.role == 2) {
                    return '文章录入员';
                }
                return '普通用户';
            })()).appendTo(row);
            $('<td/>').html('&nbsp;').appendTo(row);
            $('<td/>')
                .append((function() {
                    return $('<button type="button" class="btn btn-warning btn-xs">修改</button>')
                        .click(function(e) {
                            var m = $(this).closest('tr').data('value');
                            MPDialog.userAppend({
                                data: {
                                    uid: m.uid,
                                    loginName: m.loginName,
                                    userName: m.userName,
                                    password: m.password,
                                    role: m.role
                                },
                                confirmCallback: function () {
                                    accountViewList();
                                }
                            });
                        });
                })())
                .append((function() {
                    if (m.loginName == 'admin') {
                        return '';
                    }
                    return $('<button type="button" class="btn btn-danger btn-xs">删除</button>')
                        .click(function(e) {
                            var m = $(this).closest('tr').data('value');
                            MPDialog.confirm({
                                message: '确认删除?',
                                confirmCallback: function() {
                                    Apis.deleteAccount({uid: m.uid}, function() {
                                        accountViewList();
                                    });
                                }
                            });
                        })
                })())
                .appendTo(row);
        });
    };

    var condition = formValue($('form', panelElement));
    condition.lang = App.getLang();
    condition.siteId = App.getSiteId();
    Apis.getAccounts(condition, function(response) {
        build(response);
    });

}

/** *************************** 发布管理 */

function releaseViewList() {

    var panelElement = $('.mp-panel-release');
    var listContianer    = $('table.table-release tbody',     panelElement).empty();
    var listContianerDev = $('table.table-release-dev tbody', panelElement).empty();

    MPDialog.openWaiting();
    var build = function(response) {
        setTimeout(function() {
            MPDialog.closeWaiting();
        }, 1000);

        var list = response.data ? response.data : [];

        if (!list || list.length == 0) {
            return;
        }

        list.forEach(function(m) {
            var row = $('<tr/>').appendTo(listContianer);
            row.data('value', m);
            $('<td/>').html((function() {
                switch (m.siteId) {
                    case 'mold':
                        return '塑模版';
                    case 'press':
                        return '冲压版';
                }
            })()).appendTo(row);
            $('<td/>')
                .append(
                    $('<button type="button" class="btn btn-success btn-xs mp-preview" data-book-mode="">预览</button>')
                        .attr('data-book-mode', m.siteId)
                        .click(function(e) {
                            var siteId = $(this).data('siteId');
                            var lang = App.getLang();
                            var url = ['../manual/index.html'];
                            url.push('?siteId=' + siteId);
                            url.push('&lang=' + lang);
                            window.open(url.join(''));
                        })
                )
                .append(
                    $('<button type="button" class="btn btn-success btn-xs mp-release" data-book-mode="">发布</button>')
                        .attr('data-book-mode', m.siteId)
                        .click(function(e) {
                            var m = $(this).closest('tr').data('value');
                            var siteId = $(this).data('siteId');
                            var lang = App.getLang();
                            MPDialog.confirm({
                                message: '确认发布?',
                                confirmCallback: function() {
                                    var parameter = {};
                                    parameter.siteId = siteId;
                                    parameter.lang = lang;
                                    parameter.inside = 'false';
                                    Apis.publish(parameter, function(response) {

                                    });
                                }
                            });
                        })
                )
                .append(
                    $('<button type="button" class="btn btn-success btn-xs mp-export" data-book-mode="">导出</button>')
                        .attr('data-book-mode', m.siteId)
                        .click(function(e) {
                            var m = $(this).closest('tr').data('value');
                            var siteId = $(this).data('siteId');
                            var lang = App.getLang();
                            var url = '/support/api/article/export';
                            var parameter = {
                                siteId: siteId,
                                lang: App.getLang(),
                                title: null,
                                articleNo: null,
                                userName: null,
                                pageStart: 0,
                                pageSize: 99999,
                                orders: null,
                                detail: true
                            };
                            WJsonCall(url, parameter, function(response) {
                                window.open('/support/download/' + response.data);
                            });
                        })
                )
                .append(
                    $('<button type="button" class="btn btn-success btn-xs mp-import" data-book-mode="">导入</button>')
                        .attr('data-book-mode', m.siteId)
                        .click(function(e) {
                            var m = $(this).closest('tr').data('value');
                            var siteId = $(this).data('siteId');
                            var lang = App.getLang();
                            MPDialog.importUploadExcel({
                                siteId: siteId,
                                lang: lang,
                                callback: function() {

                                }
                            });
                        })
                )
                .appendTo(row);
        });

        list.forEach(function(m) {
            var row = $('<tr/>').appendTo(listContianerDev);
            row.data('value', m);
            $('<td/>').html((function() {
                switch (m.siteId) {
                    case 'mold':
                        return '塑模版';
                    case 'press':
                        return '冲压版';
                }
            })()).appendTo(row);
            $('<td/>')
                .append(
                    $('<button type="button" class="btn btn-success btn-xs mp-preview-dev" data-book-mode="">预览</button>')
                        .attr('data-book-mode', m.siteId)
                        .click(function(e) {
                            var siteId = $(this).data('siteId');
                            var lang = App.getLang();
                            var url = ['../manual/index.html'];
                            url.push('?siteId=' + siteId);
                            url.push('&lang=' + lang);
                            url.push('&inside=true');
                            window.open(url.join(''));
                        })
                )
                .append(
                    $('<button type="button" class="btn btn-success btn-xs mp-release-dev" data-book-mode="">发布</button>')
                        .attr('data-book-mode', m.siteId)
                        .click(function(e) {
                            var m = $(this).closest('tr').data('value');
                            var siteId = $(this).data('siteId');
                            var lang = App.getLang();
                            MPDialog.confirm({
                                message: '确认发布?',
                                confirmCallback: function() {
                                    var parameter = {};
                                    parameter.siteId = siteId;
                                    parameter.lang = lang;
                                    parameter.inside = 'true';
                                    Apis.publish(parameter, function(response) {

                                    });
                                }
                            });
                        })
                )
                .appendTo(row);
        });

    };

    var condition = {};
    condition.lang = App.getLang();
    condition.siteId = App.getSiteId();
    Apis.currentVersion(condition, function(response) {
        build(response);
    });

}


function historyReleaseViewList() {

    var panelElement = $('.mp-panel-release-history');
    var listContianer    = $('table tbody', panelElement).empty();

    MPDialog.openWaiting();
    var build = function(response) {
        setTimeout(function() {
            MPDialog.closeWaiting();
        }, 1000);

        var list = response.data ? response.data.reverse() : [];

        if (!list || list.length == 0) {
            return;
        }

        list.forEach(function(m) {
            // <th>版本</th>
            // <th>版本号</th>
            // <th>发布日期</th>
            // <th>发布者</th>
            // <th>操作</th>
            var row = $('<tr/>').appendTo(listContianer);
            row.data('value', m);
            $('<td/>').html((function() {
                switch (m.siteId) {
                    case 'Mold':
                        return '塑模版';
                    case 'Press':
                        return '冲压版';
                }
            })()).appendTo(row);
            $('<td/>').html((function() {
                if (m.versionName.indexOf('inside') > -1) {
                    return m.versionName.replace('inside', '内部参考');
                }
                return m.versionName;
            })()).appendTo(row);
            $('<td/>').html(m.versionDate).appendTo(row);
            $('<td/>').html(m.author).appendTo(row);
            $('<td/>')
                .append(
                    $('<button type="button" class="btn btn-success btn-xs">下载</button>')
                        .attr('data-book-mode', m.siteId.toLowerCase())
                        .attr('data-version-name', m.versionName)
                        .click(function(e) {
                            var siteId = $(this).data('siteId');
                            var versionName = $(this).data('versionName');
                            var lang = App.getLang();
                            // /resource/static/{lang}/{siteId}/{versionName}/download
                            var url = ['/support/resource/static'];
                            url.push(lang);
                            url.push(siteId);
                            url.push(versionName);
                            url.push('download');
                            window.open(url.join('/'));
                        })
                )
                .appendTo(row);
        });

    };

    var condition = {};
    condition.lang = App.getLang();
    condition.siteId = App.getSiteId();
    Apis.historyVersion(condition, function(response) {
        build(response);
    });

}


/** *************************** 咨询 */

function adviceViewList(pageIndex) {

    var panelElement = $('.mp-panel-advice');
    var listContianer = $('table tbody', panelElement).empty();

    MPDialog.openWaiting();
    var build = function(response) {
        setTimeout(function() {
            MPDialog.closeWaiting();
        }, 1000);

        var list = response.data ? response.data.infos : [];

        if (!list || list.length == 0) {
            return;
        }

        list.forEach(function(m) {
            var row = $('<tr/>').appendTo(listContianer);
            row.data('value', m);
            $('<td/>').html(m.name).appendTo(row);
            $('<td/>').html(m.mobile).appendTo(row);
            $('<td/>').html(m.email).appendTo(row);
            $('<td/>').html(m.company).appendTo(row);
            $('<td/>').html(m.address).appendTo(row);
            $('<td/>').html(m.content.replace(/\r\n/g, '<br />')).appendTo(row);
            $('<td/>').html(moment(m.infoDate).format('YYYY-MM-DD HH:mm:ss')).appendTo(row);
            $('<td/>')
                .append((function() {
                    if (m.loginName == 'admin') {
                        return '';
                    }
                    return $('<button type="button" class="btn btn-danger btn-xs">删除</button>')
                        .click(function(e) {
                            var m = $(this).closest('tr').data('value');
                            MPDialog.confirm({
                                message: '确认删除?',
                                confirmCallback: function() {
                                    Apis.deleteAdvice(m.id, function() {
                                        adviceViewList(pageIndex);
                                    });
                                }
                            });
                        })
                })())
                .appendTo(row);
        });
    };

    var pageSize = 10;

    var condition = formValue($('form', panelElement));
    condition.lang = App.getLang();
    condition.siteId = App.getSiteId();
    for (var i in condition) {
        if (condition[i] == '') {
            condition[i] = null;
        }
    }
    if (condition.infoStart) {
        condition.infoStart = new Date(condition.infoStart + ' 00:00:00');
    }
    if (condition.infoEnd) {
        condition.infoEnd = new Date(condition.infoEnd + ' 23:59:59');
    }
    condition.pageSize = pageSize;
    condition.pageStart = pageIndex ? (pageIndex * pageSize) : 0;
    Apis.getAdvices(condition, function(response) {
        build(response);
        var page = Pagination({
            pageStart: pageIndex,
            pageSize: condition.pageSize,
            totalSize: response.data.total
        }, function(index) {
            adviceViewList(index);
        });
        $('.pagination', panelElement).parent().empty()
            .append(page);
    });

    $('.mp-search', panelElement).unbind().click(function() {
        adviceViewList(0);
    });

    App.init.datepicker(panelElement);

}

/** *************************** 网站 */

function domainViewList() {

    var panelElement = $('.mp-panel-domains');
    var listContianer = $('table tbody', panelElement).empty();

    MPDialog.openWaiting();
    var build = function(response) {
        setTimeout(function() {
            MPDialog.closeWaiting();
        }, 1000);

        var list = response.data ? response.data : [];

        if (!list || list.length == 0) {
            return;
        }

        list.forEach(function(m) {
            var row = $('<tr/>').appendTo(listContianer);
            row.data('value', m);
            $('<td/>').html(m.siteName).appendTo(row);
            $('<td/>').html(m.siteUrl).appendTo(row);
            $('<td/>').html(m.actived ? '启用中' : '未启用').appendTo(row);
            $('<td/>')
                // .append((function() {
                //     return $('<button type="button" class="btn btn-warning btn-xs">修改</button>')
                //         .click(function(e) {
                //             var m = $(this).closest('tr').data('value');
                //             MPDialog.domainAppend({
                //                 data: {
                //                     uid: m.id,
                //                     siteName: m.siteName,
                //                     siteUrl: m.siteUrl,
                //                 },
                //                 confirmCallback: function () {
                //                     domainViewList();
                //                 }
                //             });
                //         });
                // })())
                .append((function() {
                    if (m.actived == 1) {
                        return $('<button type="button" class="btn btn-danger btn-xs">禁用</button>')
                            .click(function(e) {
                                var m = $(this).closest('tr').data('value');
                                MPDialog.confirm({
                                    message: '确认禁用?',
                                    confirmCallback: function() {
                                        Apis.activeDomain({id: m.id, isActived: false}, function() {
                                            domainViewList();
                                        });
                                    }
                                });
                            })
                    } else {
                        return $('<button type="button" class="btn btn-success btn-xs">启用</button>')
                            .click(function(e) {
                                var m = $(this).closest('tr').data('value');
                                MPDialog.confirm({
                                    message: '确认启用?',
                                    confirmCallback: function() {
                                        Apis.activeDomain({id: m.id, isActived: true}, function() {
                                            domainViewList();
                                        });
                                    }
                                });
                            })
                    }
                })())
                .appendTo(row);
        });
    };

    var condition = formValue($('form', panelElement));
    condition.lang = App.getLang();
    condition.siteId = App.getSiteId();
    Apis.getDomains(condition, function(response) {
        build(response);
    });

    // 添加网站
    $('.mp-panel-domains .mp-domain-append').unbind().click(function () {
        MPDialog.domainAppend({
            confirmCallback: function () {
                domainViewList();
            }
        });
    });
}














